Today to share with you in the Web API, how to use the ASP. NET identity to achieve Basic authentication (Basic authentication), in the blog Garden Search for a circle of Web API Basic authentication, basically do the forms certification, There is very little claims authentication (declarative authentication), while we use the ASP. NET identity to achieve login, authentication, authorization is the use of claims certification.
In the Web API2.0 authentication interface is iauthenticationfilter, we only need to implement the interface on the line. Create the Basicauthenticationattribute abstract base class to implement the Iauthenticationfilter interface:
1 Public Abstract classBasicauthenticationattribute:attribute, Iauthenticationfilter2 {3 protected AbstractTask<iprincipal> Authenticateasync (stringUserName,stringpassword, httpauthenticationcontext context,4 cancellationtoken cancellationtoken);5 Public AsyncTask Authenticateasync (httpauthenticationcontext context, CancellationToken CancellationToken)6 {7Context. Principal =NULL;8Authenticationheadervalue Authenticationheader =context. Request.Headers.Authorization;9 if(Authenticationheader! =NULL&& Authenticationheader.scheme = ="Basic")Ten { One if(!string. IsNullOrEmpty (authenticationheader.parameter)) A { -tuple<string,string> data =Getusernameandpassword (authenticationheader.parameter); -Context. Principal =awaitAuthenticateasync (data. ITEM1, data. Item2,context, CancellationToken); the } - } - - if(Context. Principal = =NULL) + { -Context. Errorresult =NewUnauthorizedresult (New[] {NewAuthenticationheadervalue ("Basic")}, + context. Request); A } at } - PublicTask Challengeasync (httpauthenticationchallengecontext context, CancellationToken CancellationToken) - { - returnTask.fromresult (0); - } - Public BOOLAllowMultiple in { - Get{return false; } to } + Privatetuple<string,string> Getusernameandpassword (stringauthenticationparameter) - { the if(!string. IsNullOrEmpty (authenticationparameter)) * { $ vardata = Encoding.ASCII.GetString (convert.frombase64string (Authenticationparameter)). Split (':');Panax Notoginseng return Newtuple<string,string> (data[0], data[1]); - } the return NULL; + } A}
View Code
where Task<iprincipal> Authenticateasync (string userName, string password, Httpauthenticationcontext context, CancellationToken CancellationToken) method for the abstract method, users can overload the implementation of their own authentication methods, forms certification, Windows certification, claims certification and so on can be.
Authenticationheadervalue authenticationheader= context. The Request.Headers.Authorization is used to obtain authentication information for the HTTP request header.
Authenticationheader.scheme = = "Basic" is used to specify the authentication mode as Basic authentication.
Authenticationheader.parameter user gets the user name and password after user encryption.
If the authentication is not empty, and the basic authentication, the head parameter is not empty, then call the specific code of authentication, if the authentication does not pass, then call the HTTP authentication context's Erroresult property:
Context. Errorresult = new Unauthorizedresult (new[] {new Authenticationheadervalue ("Basic")},context. Request); This property is set, and the browser automatically pops up the user's login window. In order for the browser to automatically eject the login window, the token authentication must be specified in the Webapiconfig configuration class, which calls the following code: CONFIG. Filters.add (New Hostauthenticationfilter (Oauthdefaults.authenticationtype)), otherwise the login form cannot be ejected.
Task Challengeasync (httpauthenticationchallengecontext context, CancellationToken CancellationToken) Method calls this method after the authentication succeeds and fails, where you can implement the logic you want, such as setting the context. The Errorresult property is not handled here, because the Authenticateasync method has been processed.
The Getusernameandpassword method is used to process the encrypted user name and password.
The next step is to implement your own authentication logic, which uses the claims authentication of the ASP.
1 Public classIdentitybasicauthenticationattribute:basicauthenticationattribute2 {3 protected Override AsyncTask<iprincipal> Authenticateasync (stringUserName,stringPassword,4 httpauthenticationcontext context, CancellationToken CancellationToken)5 {6IPrincipal principal =NULL;7 varUsermanager = context. Request.getowincontext (). Getusermanager<appusermanager>();8 varuser =awaitusermanager.findasync (userName, password);9 if(User! =NULL)Ten { OneClaimsidentity identity = A awaitusermanager.createidentityasync (user, defaultauthenticationtypes.applicationcookie); -ClaimsPrincipal ClaimsPrincipal =NewClaimsPrincipal (identity); -Principal =ClaimsPrincipal; the } - returnprincipal; - } -}
View Code
var Usermanager = context. Request.getowincontext (). Getusermanager<appusermanager> () is used for the current User Manager, and the user's additions and deletions are dependent on this object.
var user = await Usermanager.findasync (userName, password) users are found by user name and password.
Claimsidentity identity = await usermanager.createidentityasync (user, Defaultauthenticationtypes.applicationcookie) Create a user, and then create a claim by claimsPrincipal ClaimsPrincipal = new ClaimsPrincipal (identity) and return the authentication type.
As for how to create a usermanager, how to generate ASP. NET identity user, role and authentication related tables through entityframwork, there is not much to say, the garden inside more go.
Remember to encrypt the username and password in the login code and put it into the cookie, after logging in, when accessing an action that requires authentication, remember to write cookie information in the header of the HTTP request, so that the authentication filter can fetch the user information, and log in to create the cookie code snippet as follows:
Cookieheadervalue cookie = new Cookieheadervalue ("Usertoken", Authorization) { Path = "/", Domain = Request.RequestUri.Host, Expires = DateTimeOffset.Now.AddDays (7) }; ResponseMessage.Headers.AddCookies (new[] {cookie});
The client short Ajax call needs to validate the action method as follows:
function ajaxop (URL, type, data) { $.ajax ({ url:url, type:type, data:data, beforesend:function (XHR) { xhr.setrequestheader (' Authorization ', ' Basic ' + $.cookie ("Usertoken"));}} );
where Beforesend:function (XHR) {xhr.setrequestheader (' Authorization ', ' Basic ' + $.cookie ("Usertoken")) The property setting is used to get cookie information on the request header.
The action that needs to be called remembers adding the [identitybasicauthentication] attribute.
All right, here we go.
Web API Basic authentication based on ASP.