An introduction to the Identity of ASP (iii)

Source: Internet
Author: User

Objective

In the previous article, we studied the Cookieauthentication middleware, and this article mainly looks at the Identity itself.

As early as 2005, when ASP. NET 2.0 began, the WEB application in the processing of authentication and authorization has a lot of changes, such as mobile phone, tablet, etc., so at that time to adapt to this change introduced the ASP. NET Membership, But with the development of time some social networking sites or programs have gathered a large number of users, such as FACEBOOK,TWITTER,QQ, this time users want to be able to use their identity in these social sites to log on to the current site, so as to exempt the registration of these trivial and necessary operations, Users also do not have to remember a large number of account passwords.

And with the development of the Internet, more and more developers are not just concerned about the writing of the specific business code, to start to focus on the application code unit testing, which is the focus of developers. So in 2008, the ASP. NET team introduced the MVC framework to help developers build unit tests easily, and developers want their membership systems to do the same.

Based on the above, the ASP.

Identity to solve the problem

Many developers say they do not want to use identity, their own implementation to be more convenient, OK, then the need to come? Here's what I'm proposing to you for this mission.

Identity system

    • Can be used by all ASP. NET Framework (Web mvc,web forms,web api,signalr)
    • Can be used to build Web, mobile, storage, or hybrid applications.

Ability to easily extend user profile

    • Can be extended for user profiles.

Persistence of

    • By default, user information is stored in the database and can be persisted using EF. ( as you can see, EF is actually just a function point of the identity )
    • You can control the database schema, change the table name or the data type of the primary key (int,string)
    • Different storage mechanisms (such as NOSQL,DB2, etc.) can be used

Unit Test

    • Enables a Web application to be unit tested and can write unit tests for ASP.

Role mechanism

    • Provides a role mechanism that allows you to use different roles to restrict different permissions, easily create roles, add roles to users, and so on.

To support claims-based

    • A Claims-based authentication mechanism is required, where the user identity is a set of Claims, a set of Claims can be more expressive than the role, and the role is merely a bool value to represent the member.

Third party Social Login

    • It is convenient to use third-party login, such as Microsoft account, Facebook, Twitter,google, etc., and store user-specific data.

Encapsulation as middleware

    • Based on middleware implementation, do not rely on specific projects
    • Based on Authorzation middleware implementations, rather than using FormsAuthentication to store cookies.

NuGet Package provides

    • Released as a Nuget package, which makes it easy to iterate and bug fix, which can be flexibly provided to the user.

Above, is the demand that I put forward, if let you to encapsulate such a user authentication component, you will not think of these function points above, that for these function point how will you design?

Let's take a look at how the Identity is designed.

Getting Started

Cobwebs, let's look at the way we use it from the entrance. First we open the Startup.cs file and add the following code:

public class Startup{    public void ConfigureServices(IServiceCollection services)    {        services.AddDbContext<ApplicationDbContext>(options =>                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));                services.AddIdentity<ApplicationUser, IdentityRole>(options => {            options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie";            options.Cookies.ApplicationCookie.CookieName = "Interop";        })        .AddEntityFrameworkStores<ApplicationDbContext>()        .AddDefaultTokenProviders();    }        public void Configure(IApplicationBuilder app)    {        // 使用了 CookieAuthentication 中间件做身份认证        app.UseIdentity();    }}

In Configureservices, we first register the database context, and then services.AddIdentity() we look at what services are registered in it?

public static Identitybuilder Addidentity<tuser, trole> (this iservicecollection services, Action<identityo Ptions> setupaction) where tuser:class where trole:class{//This is the services that are used by the Identity. Addauthentication (Options + =//This is the Default value for Externalcookieauthenticationscheme opt Ions. Signinscheme = new Identitycookieoptions ().    Externalcookieauthenticationscheme;    }); Registration of Ihttpcontextaccessor will use the services.        Tryaddsingleton<ihttpcontextaccessor, httpcontextaccessor> (); Identity Services Services.    Tryaddsingleton<identitymarkerservice> (); Services.    Tryaddscoped<iuservalidator<tuser>, uservalidator<tuser>> (); Services.    Tryaddscoped<ipasswordvalidator<tuser>, passwordvalidator<tuser>> (); Services.    Tryaddscoped<ipasswordhasher<tuser>, passwordhasher<tuser>> (); Services. Tryaddscoped<ilookupnormalizer, UpperinvariantlookupnormAlizer> (); Services.        Tryaddscoped<irolevalidator<trole>, rolevalidator<trole>> (); Error description Information Services.    Tryaddscoped<identityerrordescriber> (); Services.        Tryaddscoped<isecuritystampvalidator, securitystampvalidator<tuser>> (); Identity Party factory services.        Tryaddscoped<iuserclaimsprincipalfactory<tuser&gt, Userclaimsprincipalfactory<tuser, TRole>> (); Three major Object Services.    Tryaddscoped<usermanager<tuser>, usermanager<tuser>> (); Services.    Tryaddscoped<signinmanager<tuser>, signinmanager<tuser>> (); Services.    Tryaddscoped<rolemanager<trole>, rolemanager<trole>> (); if (setupaction! = null) {services.    Configure (setupaction);     } return new Identitybuilder (typeof (TUser), typeof (Trole), services);}

After looking at the above code, basically know the Identity of his design of a framework, through this structure we can also learn how we encapsulate a middleware, how to organize our code structure, how to use the ASP. NET Core to provide us with the dependency injection for better decoupling, Let's take a look at what we can learn from the above code:

1, in public static IdentityBuilder AddIdentity<TUser, TRole>(this IServiceCollection services, Action<IdentityOptions> setupAction) This extension method, provides a parameter, what Action<IdentityOptions> is the use of this? This is when we design a middleware, there are parameters that need to be provided externally, we will design an Options class to accept external parameters and then encapsulate them as an action delegate. In the use of the place can be injected in the form of ioption xxx used.

2, services.TryAddScoped<Interface,Implement>() This registration means that if the DI container is detected in the current to register the interface or service, it will not be registered again, will not register in. So why do you use it here? This is because if the user has implemented this interface and is already registered in the container, it is used by the user registration, not the middleware itself. Users will be able to customize the functionality provided by the middleware, which is the polymorphism in Oo, this is the Richter scale substitution principle.

3, if you can understand the 2nd article, then you should know why in the service to register the error description information that IdentityErrorDescriber , also can solve you want to prompt account password error, but the identity output is the English question hint.

4, three objects, this is the identity of the core, so learning identity, in the blog after reading the identity of ASP (one, two), learn these three objects is enough.

Signinmanager: Mainly deals with the business logic of registering login.

Usermanager: Handle user related add Delete, change password, add delete role, etc.

rolemanager: Role-related ADD delete update, etc.

Some students may be very curious, are not dependent on the specific database or EF, how to do the additions and deletions to check it?

This time, you need a few Store interfaces to come in handy. The following is the store interface defined in the identity:

    • Iqueryablerolestore
    • Iqueryableuserstore
    • Iroleclaimstore
    • Irolestore
    • Iuserauthenticationtokenstore
    • Iuserclaimstore
    • Iuseremailstore
    • Iuserlockoutstore
    • Iuserloginstore
    • Iuserpasswordstore
    • Iuserphonenumberstore
    • Iuserrolestore
    • Iusersecuritystampstore
    • Iuserstore
    • Iusertwofactorstore

With these interfaces, it is not enlightened, the original Identity is implemented in this way the persistence mechanism, relying on abstract interfaces rather than relying on specific details of implementation, this is the object-oriented dependency inversion principle ah.

Identity and EntityFramework

Identity and entityframework relationship, I believe the last chapter to understand, it is easy to understand, right, EF just for the above-mentioned Store interface implementation, do not believe you look at the source:

The class files that begin with the Identity are defined as entity objects that need to be persisted, and those at the end of the store are the implementations of the interfaces.

The Identity implementation of the third party

In addition to the EF is the official default provided by the persistence of the library, there are some third-party libraries, of course, you can also use ADO or Drapper.

MANGODB implementations for Identity: Https://github.com/tugberkugurlu/AspNetCore.Identity.MongoDB

LINQTODB implementations for Identity: https://github.com/linq2db/LinqToDB.Identity

Summarize

This blog post has been written for a long time, on the one hand because of the idea of how to make people better understand, and not just use. Because there are too many articles about the use of identity and code, but in the end people will not use. It was important to think of the background of the birth if it was necessary to make others want to understand your library or code, because that was the purpose of the design. On the other hand, the. NET Core release of the 1.1 release at Connect () 2016, in addition to upgrading the project to 1.1, is also learning 1.1 new things to better share with you.

To give people to fish than to give people to fishing, a good blog is really to spend the author more effort and time. If you think this blog post is helpful, thank you for your "recommendation".

At the same time, the Identity series of the ASP is over, thanks to the support of friends. If you are interested in. NET core and can follow me, I will regularly share my learning experiences on. NET core with my blog.

This address: http://www.cnblogs.com/savorboard/p/aspnetcore-identity3.html
Author Blog: Savorboard
Welcome reprint, please give the source and link in obvious position

An introduction to the Identity of ASP (iii)

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.