Who is AspNet Identity and Owin, aspnetowin

Source: Internet
Author: User
Tags set cookie

Who is AspNet Identity and Owin, aspnetowin

Http://tech.trailmax.info/2014/08/aspnet-identity-and-owin-who-is-who/.

 

Recently I found that Stackoverflow has a very good question. Q: Why can I still add the claim to the Identity and persist it to the cookie after calling AuthenticationManager. SignIn.

The sample code is as follows:

ClaimsIdentity identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie );var claim1 = new Claim(ClaimTypes.Country, "Arctica");identity.AddClaim(claim1);AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, identity );var claim2 = new Claim(ClaimTypes.Country, "Antartica");identity.AddClaim(claim2);

Yes, why does claim2 still work after the cookie is set.

After in-depth research, I found that the AspNet Identity framework does not set cookies, but the OWIN is set. The OWIN is part of the Katana open-source project. it is a good thing to have source code available-you can find out why things do not work as expected.

In this case, I spent some time exploring how the Katana project and AuthenticationManager work. it turns out that the SignIn method does not set cookie. it stores the Identity object in the memory until the response time is reached, and claims is converted to a cookie, so everything works magically -)

This raises another problem. Currently, there is no open source code for Identity, so what role does OWIN play in Identity and how does Claims work?

The results show that the Identity framework only processes user persistence, password hashing, verifies that the password is correct, and sends Password Reset emails. however, Identity does not actually verify users or create cookies. cookies are processed by OWIN.

Check the logon code:

public async Task SignInAsync(Microsoft.Owin.Security.IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent){    authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);    ClaimsIdentity identity = await UserManager.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);    authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties() { IsPersistent = isPersistent }, identity);}

Identity only creates ClaimsIdentity (Learning Website ReferenceSource), while ClaimsIdentity is.. Net framework, rather than nuget packages from the Internet. the ClaimsIdentity is then passed to the AuthenticationManager that owns the OWIN that sets the cookie callback, while the AuthenticationManager has a callback that sets cookies when writing the response header.

So far, it has been very good. There are three parts: the Identity framework creates a ClaimsIdentity, The OWIN creates a cookie Based on the ClaimsIdentity, And the. Net framework controls the ClaimsIdentity class.

When you want to access ClaimsPrincipal. Current in your class, you only use the. Net framework and do not need to use other class libraries. This is very convenient!

 

Default Claims

The Identity framework does a very beautiful thing for you. By default, When you log on, it adds some claims to a principal, as shown below:

  • User. Id: the type is"Http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"Or ClaimTypes. NameIdentifier.
  • Username: the type is"Http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"Or ClaimTypes. Name.
  • "ASP. NET Identity": Save as"Http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider". This is useful when you use OpenId for verification. However, it is useless if you only use the database to store users. Click here for more information.
  • Guid containing the user's security postmark. The persistence type in Claim is"AspNet. Identity. SecurityStamp". The security postmark is a major snapshot of the user's status. If the verification password/method, email, and so on change, the security postmark will change, this allows you to "log out anywhere" by changing the certificate ". obtain more information about the security postmark from Kung's answer.
  • The most useful claims is role. All the role assigned to the user is saved as ClaimTypes. Role or"Http://schemas.microsoft.com/ws/2008/06/identity/claims/role". So next time you need to check the roles of the current user and check this claims. It will not be searched in the database. This is very fast. in fact, if you call ClaimsPrincipal. isInRole ("RoleName"), the framework will enter claims and check whether the user has allocated the specified Role.

You can view these claim types on the. Net Reference website. This list is not complete. you can create your own claim type-a string.

If you want to add your own owin claim type, we recommend that you use your own symbol, for example:"MyAppplication: GroupId"And keep all claim types as constants in a class:

public class MyApplicationClaimTypes{    public string const GroupId = "MyAppplication:GroupId";    public string const PersonId = "MyAppplication:PersonId";    // other claim types} 

In this way, you can always find the claims, and it will not conflict with the claim type in the framework, unless your claims is of the same type as the claims type in the framework, such as ClaimTypes. Email.

 

Add the default claims

I always add the user's email to the claims list during user logon, as shown in claim1 and claim2 in the previous example:

public async Task SignInAsync(IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent){    authenticationManager.SignOut(        DefaultAuthenticationTypes.ExternalCookie,        DefaultAuthenticationTypes.ApplicationCookie);    var identity = await this.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);    // using default claim type from the framework    identity.AddClaim(new Claim(ClaimTypes.Email, applicationUser.Email));    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);}

You can add the default claims for all users here, but there is an IClaimsIdentityFactory class (assigned to UserManager) with only one method:

public interface IClaimsIdentityFactory<TUser, TKey> where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>{    /// <summary>    /// Create a ClaimsIdentity from an user using a UserManager    /// </summary>    Task<ClaimsIdentity> CreateAsync(UserManager<TUser, TKey> manager, TUser user, string authenticationType);}

The default Implementation of AspNet Identity is: Create ClaimsIdentity, add the default claims as described above, and store the claims of IdentityUserClaims type in the database for the user. you can override this implementation and insert your own logic/claims:

public class MyClaimsIdentityFactory : ClaimsIdentityFactory<ApplicationUser, string>{    public override async Task<ClaimsIdentity> CreateAsync(UserManager<ApplicationUser, string> userManager, ApplicationUser user, string authenticationType)    {        var claimsIdentity = await base.CreateAsync(userManager, user, authenticationType);        claimsIdentity.AddClaim(new Claim("MyApplication:GroupId", "42"));        return claimsIdentity;    }}

And then assign it to UserManger:

public UserManager(MyDbContext dbContext)    : base(new UserStore<ApplicationUser>(dbContext)){    // other configurations    // Alternatively you can have DI container to provide this class for better application flexebility    this.ClaimsIdentityFactory = new MyClaimsIdentityFactory();}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.