Web API is based on the Basic Authentication of ASP. NET Identity,
Today, we will share with you how to use ASP. NET Identity implements Basic Authentication. In the blog garden, you searched for a circle of Basic Web API Authentication, which is basically Forms Authentication, with few clims certifications (declarative Authentication ), we are using ASP. NET Identity implements logon, authentication, and Claims authentication.
In Web API2.0, the authentication interface is IAuthenticationFilter. You only need to implement this interface. Create a BasicAuthenticationAttribute abstract base class to implement the IAuthenticationFilter interface:
1 public abstract class BasicAuthenticationAttribute: Attribute, IAuthenticationFilter 2 {3 protected abstract Task <IPrincipal> AuthenticateAsync (string userName, string password, HttpAuthenticationContext context, 4 CancellationToken cancellationToken ); 5 public async Task AuthenticateAsync (HttpAuthenticationContext context, CancellationToken cancellationToken) 6 {7 context. principal = null; 8 AuthenticationHeaderValue authenticationHeader = context. Request. Headers. Authorization; 9 if (authenticationHeader! = Null & authenticationHeader. Scheme = "Basic") 10 {11 if (! String. isNullOrEmpty (authenticationHeader. parameter) 12 {13 Tuple <string, string> data = GetUserNameAndPassword (authenticationHeader. parameter); 14 context. principal = await AuthenticateAsync (data. item1, data. item2, context, cancellationToken); 15} 16} 17 18 if (context. principal = null) 19 {20 context. errorResult = new UnauthorizedResult (new [] {new AuthenticationHeaderValue ("Basic")}, 21 context. reque St); 22} 23} 24 public Task ChallengeAsync (HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) 25 {26 return Task. fromResult (0); 27} 28 public bool AllowMultiple29 {30 get {return false;} 31} 32 private Tuple <string, string> GetUserNameAndPassword (string authenticationParameter) 33 {34 if (! String. isNullOrEmpty (authenticationParameter) 35 {36 var data = Encoding. ASCII. getString (Convert. fromBase64String (authenticationParameter )). split (':'); 37 return new Tuple <string, string> (data [0], data [1]); 38} 39 return null; 40} 41}View Code
The Task <IPrincipal> AuthenticateAsync (string userName, string password, HttpAuthenticationContext context, CancellationToken cancellationToken) method is an abstract method. You can reload your own authentication methods, Forms authentication, Windows authentication, claims authentication and so on.
AuthenticationHeaderValue authenticationHeader = context. Request. Headers. Authorization is used to obtain the authentication information of the HTTP Request header.
AuthenticationHeader. Scheme = "Basic" is used to specify the Authentication mode as Basic authentication.
AuthenticationHeader. Parameter the user obtains the user name and password encrypted by the user.
If the authentication is not empty and Basic authentication and the header parameter is not empty, the specific authentication code is called. If the authentication fails, the ErroResult attribute of the HTTP Authentication context is called:
Context. ErrorResult = new UnauthorizedResult (new [] {new AuthenticationHeaderValue ("Basic")}, context. Request); if this attribute is set, the browser automatically displays the user logon window. To automatically display the logon window in the browser, you must specify the Token Authentication in the WebApiConfig configuration class, that is, call the following code: config. filters. add (new HostAuthenticationFilter (OAuthDefaults. authenticationType); otherwise, the logon form cannot be displayed.
The Task ChallengeAsync (HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) method calls this method after the authentication succeeds or fails. You can implement the desired logic here, such as setting context. the ErrorResult attribute is not processed here, because the AuthenticateAsync method has already 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. Here we use the Claims authentication of Asp.net Identity.
1 public class Partition: BasicAuthenticationAttribute 2 {3 protected override async Task <IPrincipal> partition (string userName, string password, 4 encryption context, CancellationToken cancellationToken) 5 {6 IPrincipal principal = null; 7 var userManager = context. request. getOwinContext (). getUserManager <AppUserManager> (); 8 var user = await use RManager. FindAsync (userName, password); 9 if (user! = Null) 10 {11 ClaimsIdentity identity = 12 await userManager. createIdentityAsync (user, DefaultAuthenticationTypes. applicationCookie); 13 ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal (identity); 14 principal = claimsPrincipal; 15} 16 return principal; 17} 18}View Code
Var userManager = context. Request. GetOwinContext (). GetUserManager <AppUserManager> () is used for the current user manager. User addition, deletion, modification, and query operations depend on this object.
Var user = await userManager. FindAsync (userName, password) The user finds the user based on the user name and password.
ClaimsIdentity identity = await userManager. CreateIdentityAsync (user, defaauthauthenticationtypes. ApplicationCookie.
As for how to create UserManager, how to use Entityframwork to generate Asp.net Identity users, role and Authentication related tables, I will not talk about it here. There are more in the garden.
Remember to encrypt the user name and password in the login code and put them in the Cookie. After logging in, remember to write Cookie information in the HTTP request header when accessing an Action that requires authentication, in this way, the authenticated Filter can obtain the user information. The Cookie code snippet for Logon creation is as follows:
CookieHeaderValue cookie = new CookieHeaderValue("userToken", authorization) { Path = "/", Domain = Request.RequestUri.Host, Expires = DateTimeOffset.Now.AddDays(7) }; responseMessage.Headers.AddCookies(new[] {cookie});
The method for verifying the short AJax call is as follows:
function ajaxOp(url, type, data) { $.ajax({ url: url, type: type, data: data, beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Basic ' + $.cookie("userToken")); } }); }
BeforeSend: function (xhr) {xhr. setRequestHeader ('authorization', 'Basic '+ $. cookie ("userToken") attribute settings are used to obtain Cookie information and put it in the request header.
Remember to add[IdentityBasicAuthentication] feature.
Now, let's go here.