I. Forms certification 1, Enable forms certification in WEBAPI projects
Why: How do I use Forms authentication in WEBAPI? Because other projects are using forms authentication.
What is the forms certification? It is a messagehandle in Webapi, please look for the keyword "ASP. NET Forms"
How to: How do I start forms certification?
The simplest is to start the forms certification by configuring:
1 <system.web>2 <AuthenticationMode= "Forms">3 <Formsname=". Formscookie "loginurl= "/login.aspx"Protection= "All"Timeout= "43200"Path="/"Defaulturl= "Http://www.cnblogs.com"Domain= ". Cnblogs.com"cookieless= "UseCookies" />4 </Authentication>5 <httpcookieshttponlycookies= "true" />6 </system.web>7 <system.webserver>
View Code
Simply say how forms authentication works: First in a pipeline, forms reads the associated cookie in the request, decrypts it, authenticates it, and writes the result of the authentication to the request context and the identity attribute of the thread. Then the request continues to go back, and when the resulting response is returned in the pipeline, forms will determine if the response is 401, then the address of the location to the Loginurl setting in the configuration and change the status to 302.
2. Several attribute
Why: What do you know about attribute? Because the results of the forms authentication are written into the identity attribute, we generally want to get the property, determine if the authentication is successful, if the failure returns 401, and so on, and so on a lot of processing. Is it a lot of trouble? Yes, wrap it up and write one yourself? Of course, in fact, Microsoft Dafa has long been considered, for the general scene of the processing logic are encapsulated, they are called
Authorizeattribute, Allowanonymousattribute, are attribute.
What: What are these attribute? as the name implies, Authorizeattribute only allows authentication through the request, Allowanonymousattribute allows anonymous requests.
How: So how to use it? It's simple. They can function on types, methods, so you can register globally, controller, action, so easy!
3. Override the validation failure method in Unauthorize
Why: Because if response status = = 401, then forms will be location to the loginurl in the configuration (a default value of "Login.aspx" is generated even if it is not configured manually), and the status is set to 302. If the client is a browser, then it will jump directly to not capture this state, which is not appropriate in many scenarios, such as: Spa (single page application), we do not want it to automatically jump to the landing page, but give a hint, let the user choose whether to log in. So you want to rewrite the processing logic for authentication failures in forms.
How: There is a virtual method handleunauthorizedrequest in Authorizationfilterattribute that overrides it to implement the custom processing logic. This kind of design thinking is very good, can learn more.
/// <summary> ///If unauthorize return 403 instead of 401, avoid redirect. /// </summary> Public classForbiddenlocationauthorizeattribute:authorizeattribute {protected Override voidhandleunauthorizedrequest (Httpactioncontext actioncontext) {httpresponsemessage response=NewHttpresponsemessage (); Response. StatusCode=System.Net.HttpStatusCode.Forbidden; Actioncontext.response=response; } }
Use 403 (Forbidden) instead of 401, so you can avoid the automatic jump of forms. While this may be a disadvantage, it is an effective solution.
Second, Modelvalidata (model validation)
1. Why
There is no user input where the parameter verification, which is not only a security issue, but also to ensure that the data is complete and correct.
2. What
WEBAPI integrates the model validation mechanism, and when the request is executed by the action, there is a model binding step, which is the parameter that matches the action, the specifics are not said, and Modelvalidata is here, It is validated based on the dataannotations (data annotations) of each attribute in the model, and ultimately saves the result in a property in the context of the action, which is actionContext.ModelState.IsValid.
3. How
A, set dataannotations for model
Public classbannerdto {[Jsonproperty (PropertyName="ID")] [Required (ErrorMessage="ID is required")] PublicGuid Id {Get;Set; } [Jsonproperty (PropertyName="title")] [Required (ErrorMessage="title cannot be empty")] [MaxLength ( $, errormessage ="title cannot exceed 200 characters")] Public stringTitle {Get;Set; } [Jsonproperty (PropertyName="src")] [Required (ErrorMessage="the picture link cannot be empty")] [MaxLength ( -, errormessage ="Image link cannot exceed 500 characters")] Public stringImageuri {Get;Set; } [Jsonproperty (PropertyName="href")] [Required (ErrorMessage="The hyperlink cannot be empty")] [MaxLength ( -, errormessage ="The hyperlink cannot exceed 500 characters")] Public stringHref {Get;Set; } [Jsonignore] PublicGuid? Authorityid {Get;Set; } [Jsonignore] Public BOOLIsDeleted {Get;Set; } =false; [Jsonproperty (PropertyName="CreateDate")] PublicDateTime CreateDate {Get;Set; } }
Ps:[jsonproperty], [Jsonignore] are some related settings that specify JSON serialization, set aliases, ignore, and so on. Returns the name of the elegant variable, guaranteeing the code style.
For the use of DataAnnotations, please see MSDN, too simple. When the validation fails, the constraints and errormessage are set, and the ErrorMessage is returned.
b, using the filter method to add validation to the action, the benefit is not much to say.
Public class Validatamodelattribute:actionfilterattribute { publicoverridevoid onactionexecuting (Httpactioncontext actioncontext) { if (! ActionContext.ModelState.IsValid) { = ActionContext.Request.CreateErrorResponse ( Httpstatuscode.badrequest, actioncontext.modelstate); }}}
Don't forget to inject this filter into the httpcomfiguration.
// Model Validation Config. Filters.add (new Validatamodelattribute ());
For an action that you do not want to validate, you can use Overrideactionfilters to override all Fiters set by the ancestor.
Modelvalidate failed requests will receive a 400 response, and all errormessage will be in the response message, for example:
{"Message":"therequest is invalid. ","modelstate": {"Sub. Href": [" hyperlink cannot be null "]}}
Using Forms authentication and Modelvalidata (model Validation) in ASP. WebAPI