In addition to providing cookie-based authentication, ASP.NET Identity also provides some advanced functions, such as locking users and prohibiting logins after repeatedly inputting incorrect account information, integrating third-party authentication, and secondary authentication of accounts, etc. These functions are included in the default template of ASP.NET MVC.

This article explains how ASP.NET Identity implements authentication from the following aspects: ● multiple authentication of ASP.NET Identity ● positive and negative mode of Owin authentication ● Owin authentication mechanism ● authentication solution based on Owin Identity in ASP.NET

ASP.NET Identity’s “multiple” authentication

Why is this chapter about multiple authentication of Identity? Because ASP.NET Identity is based on authentication implemented by Owin in the form of middleware, here is the code added in the default template:

  

As you can see from the code, the template code adds a total of seven (including three annotated) authentication-related middleware, each of which will be executed as a request enters the Owin pipe. The above authentication middleware includes cookie-based, external cookie-based, two-factor authentication, and third-party account logins (annotated code) by function, which means that each request is handled individually by these middleware, hence the term “multiple” authentication. This article from the title to the present “multiple” are quoted, indicating that Identity authentication is not as simple as the surface of multiple functions stack, then from the positive and negative mode of authentication to eliminate Identity in ASP.NET authentication fog.

Positive and negative patterns for Owin authentication

Identity realizes authentication based on Owin, so IN fact Owin is the maker of authentication rules. Identity is only one kind of implementation. In Owin, authentication middleware is divided into two modes, namely positive mode and negative mode. Both modes are defined by an enumerated type called AuthenticationMode:

    

● Active mode: The authentication middleware in Active mode modifies the user identity information when the request arrives and processes the response information when the response status is 401. ● Passive mode (Passive mode) : The middleware in this mode will only use the method contained in the middleware to verify the request when it is needed or explicitly called, including that when 401 occurs, processing will be invoked only after the corresponding verification type name match is found in the expanded Challenge data.

The bottom line is that no matter how many authentication middleware are added to the Owin pipeline, requests will only be processed if the authentication mode is active, and everything else will need to be invoked manually. Why is that? Read the rest.

Talk about Owin authentication

ASP.NET without magic — Identity and Owin “, ASP.NET without magic — ASP.NET Identity encryption and decryption “and other articles. However, it mainly introduces how Identity is added to Owin pipeline through middleware and what it does for user Identity information authentication and cookie-based authentication middleware. The core point is not mentioned, that is, the whole authentication mechanism or rules are determined by Owin(Katana). Identity is nothing more than an implementation or even a consumer that follows this rule, as it simply provides user data to the Cookie authentication middleware and then extends the authentication functionality in ASP.NET by relying on AuthenticationManager.

  

Micrsosft.Owin defines owIN-related principals such as context, pipeline Builder, and AuthenticationManager, the authentication related business logic. 2. Microsoft.owin. Security complements Owin’s security-related capabilities by defining authentication patterns (active and passive) and middleware and processor base classes for authentication. 3. Microsoft. Owin. Security. XXX type as real authentication logic implementer provides different kinds of cookies, Token based even escrow account authentication logic. 4. Microsoft. AspNet. Identity. There are two main Owin object, SignInManager encapsulates the business logic of the login, the business logic includes the operation of the user data (UserManager) and authentication logic, Provides a common login, double factor higher functions such as login, external account login, and AuthenticationManagerExtensions is also aimed at these advanced features of exploring the AuthenticationManager.

AuthenticationManager

AuthenticationManager is the core of the authentication service in Owin, and its interface is defined as follows:

  

You can see from the comments that it is used to interact with the authentication middleware that is concatenated to the pipe and provides authentication AuthenticateAsync, reject Challenge (I translate reject or Challenge, etc.), In other words, authentication failed), login SignIn, logout SignOut, and GetAuthenticationTypes. An AuthenticationManager is created for each request, which carries the User information for the current request, User, and then manages all the authentication middleware cascaded to the Owin pipe. Through this series of middleware to complete the user verification and rejection, login and logout and other functions.

Note that AuthenticateAsync returns an authentication result that contains user information in addition to the authentication result, while SignIn actually adds (or replaces) user information to the current request context. So most of the time the AuthenticateAsync and SignIn methods are used consecutively.

AuthenticationMiddleware&AuthenticationHandler

AuthenticationMiddleware and AuthenticationHandler, as template code, restrict how middleware can execute and how the processor can handle it:

  

There are four stages: 1. Processor creation. 2. Initialize the processor. 3. Processor invocation. 4. Processor destruction.

For AuthenticationHandler, it has several important procedures: 1. Initialization: Registers the current processor with AuthenticationManager, and calls the authentication method if the current middleware is in active mode, otherwise the authentication method can only be called through AuthenticationManager. (Note: The specific implementation of InitializeCoreAsync is in the subclass)

  

2. Perform:

As you can see from the above analysis, there is a method, AuthenticateAsync, which is used for authentication. What does the execution method do? Authentication methods in identity-based ASP.NET applications only authenticate requests automatically when in active mode and do nothing to the request whether or not it is authenticated (even if it is not authenticated, the request can still be sent to Controller, Action execution, Because they can be called anonymously), and there is a case that when the server processes the request, it can determine how the request should be handled. For example, after logging in through a third-party account, some Token information will be carried in the QUERY string of THE Url. Instead of handing the request to the Controler for processing, in which case the processing logic can be placed in the Invoke method. If the Invoke method returns true, The pipe will no longer execute further down (see middleware’s Invoke method). When verifying social accounts such as Microsoft and Google, its authentication logic is written in the InvokeAsync method, while the middleware of Cookie authentication returns false by default and passes the request to subsequent components for processing. The third party authentication of Owin will be introduced in detail later.

  

3. The destroyed: When the request is in the return phase, it triggers the authentication processor’s destruction process, which consists of writing the identity information to the response information (for example, Cookie authentication serializes and encrypts the AuthenticationTicket object and writes it to the Cookie) and performing some destruction logic of subclasses. Finally, the processor added to AuthenticationManager is removed.

  

SignInManager&AuthenticationManagerExtensions

SignInManager is used to manage user logins such as logins, logins with passwords, double-factor logins, external logins, etc. It is the encapsulation of UserManager and AuthenticationManager:

  

AuthenticationManagerExtensions is to extend the AuthenticationManager, mainly for the AuthenticationManager added external validation and additional support double factor authentication, These extension methods are used by SignInManager and authentication Controller:

  

Owin-based Identity in ASP.NET authentication solution

The main components and functions of Owin and Identity are described above. How do you use these functions to implement authentication in ASP.NET? Mainly the authentication in ASP.NET is divided into the three types: low normal validation: ordinary before validation is introduced in the article based on Cookie authentication way, the process is the user submits the user name and password, the server after completion generated password authentication of user information, subsequent requests according to the user information to authenticate users. Low double factor authentication: double factor authentication on the basis of normal verification increased such as message authentication code, mail verification code information of the second validation, that is to say the server according to the user name password after complete the user authentication, the user is still in a “failed” state of authentication, also need to send to customer verification code for the secondary check after finish the authentication. ● External authentication: the user data outside the application, such as a variety of social accounts, login through the authentication interface provided by these service providers, return a series of service access Token, user information and other authentication methods.

I’ll show you how these three approaches are implemented using the Identity component using ASP.NET MVC template code with authentication capabilities.

Ordinary validation

Identity implements common user authentication through Cookie authentication in ASP.NET. The main process is as follows (note: on the left is the main process, and on the right is the sub-process contained in each main process) :

  

 

ASP.NET MVC implements cookie-based user authentication through Identity. It has several points to note:

1. First, the user name and password are submitted to the server through the Login method in AccountControllter, which can be accessed anonymously. Then, the user name and password are verified and logged in through PasswordSignInAsync of SignInManager. Finally, the user’s identity information is encrypted and written to the Cookie in the request return stage.

2. In the password authentication/login phase, in addition to verifying the user password, you can determine whether the user is locked, count the number of login failures, and reset the user, which is used to lock the user and automatically lock the user after multiple login failures.

3. SignInManager. SignInOrTwoFactor method is decided by the configuration of the validation method double factor authentication or ordinary validation, in ordinary validation case, through the user identity information and new authentication attribute to complete the subsequent validation manager login operation (note: As mentioned in the introduction to the authentication manager, its AuthenticateAsync and SignIn methods are used in sequence, the former getting user information, the latter writing user information to the request context, but since this is a login operation, there is no user identity information in the request. Therefore, the user identity information and authentication attributes need to be created by ourselves, such as through the database. In this case, the user information is created by ourselves and then the SignIn method is used to log in and write the user information to the request context.

4. When the request is returned, the user information written to the request context is carried to the client in the form of cookies for authentication of subsequent requests.

  

The figure above shows the authentication process when the user accesses other resources after login. The whole process here is completed by Cookie authentication middleware. The following points need to be noted:

1. The Cookie authentication middleware is in active mode by default, so the AuthenticateAsync method will be called during processor initialization to parse and verify the identity information Cookie in the request.

2. When the authentication of the identity information is complete, the middleware writes the user information to the request context through the method AddUserIdentity (which actually replaces the SignIn method of AuthenticationManager).

3. When the request returns stage, if the status is normal, then continue to identity information write a Cookie, but if the authentication failed (e.g., timeout, and so on and so forth), request return to the processor ApplyResponseChallengeAsync processing (e.g., jump to the login page, etc).

Two-factor verification

Two-factor authentication is the introduction of a second authentication on top of normal authentication, that is, there will be two requests for login:

  

 

The figure above shows the process of two-factor authentication. Two-factor authentication is actually based on ordinary authentication. It is only enabled in the form of configuration.

1. On the first login, as with normal authentication, you need to verify the user’s password, whether they are locked, and so on. Then, since two-factor authentication is required, you create a TwoFactorCookie identity and execute the manager’s SignIn method, which holds the password-authenticated user name. App. After completion of the request UseTwoFactorSignInCookie method to add a Cookie validation middleware will be created above TwoFactorCookie identity information about cookies (note: Authentication middleware with multiple cookies is added to the pipeline, but its configuration and authentication type are different, where the middleware is selected to handle generating cookies based on the authentication mode of user information, whereas the value passed in by the ClaimsIdentity construct is the authentication mode).

  

2. ASP.NET MVC program redirects the first verification request to the verification code sending (select the sending mode) and verification code filling page. After filling in the verification code and submitting it, the second verification is entered.

3. During the second verification, the AccountController’s VerifyCode method is verified by SignInManager’s TwoFactorSignInAsync method. Is the core of the method through the AuthenticationManager explicit calls the “TwoFactorCookie” validation, the validation is app. UseTwoFactorSignInCookie method to add a negative mode of authentication middleware. (Note: The value of the TwoFactorCookie constant is TwoFactorCookie, and the SignIn method of AuthenticationManager finds and calls the corresponding authentication method by string matching.)

  

This authentication method is to obtain the last stored Cookie and decrypt it to obtain the user name. After obtaining the corresponding user information, the verification code is verified by the UserTokenProvider. When all the information is verified, The user information will be added to the request context using the SignIn method of AuthenticationManager (note: Verification code generation and verification will be covered in a subsequent section).

4. When VerifyCode requests and responds, user information is written into cookies through Cookie middleware in active mode, which is consistent with common verification.

Note: The subsequent requests are the same as normal authentication, using the identity information carried by the Cookie and authenticating through the Cookie authentication middleware in active mode.

External validation

External authentication refers to the transfer of user identity authentication to external servers (such as social platforms). Compared with the above two authentication processes, the external authentication process is more complex, and its flow chart is as follows:

(note: because the flow chart is too large, it is divided into two parts. The first part is the jump to the login page of the third party, and the second part is the ASP.NET authentication process that the third party redirects back after login.)

  

ASP.NET third-party login page adjustment process is relatively simple. In the default template project, the entire function is initiated by the ExternalLogin Action method in the AccountController. The first step is to select a third-party account login method on the page and submit it to the server. The ExternalLogin method directly rejects the current request through AuthencationManager’s Challenge method, redirecting the request to a third-party login page.

  

 

If the third party successfully logs in, the ExternalLoginCallback of the AccountController is reconfigured. The process is described as follows:

1. The first thing you need to mention is a template project in authentication duct through the app. UseExternalSignInCookie method to set the default login authentication method (ExternalCookie) and add the Cookie validation of a negative mode middleware, The authentication method is also ExternalCookie.

  

2. As the request carries information authenticated by Microsoft (Microsoft as an example here), it will be processed by the Invoke method of the specific authentication middleware. The process is to Invoke the corresponding authentication method to obtain the identity information and add the default authentication type to the authenticated identity information (Note: This default type is ExternalCookie, which is intended to treat all third-party authenticated accounts in the same way), and finally writes the identity information to the context using the SignIn method, returning True. As mentioned above, nothing will be called when the Invoke method of the authentication handler returns true).

3. In the return process from Microsoft authentication processing middleware, the user information in the context is ExternalCookie, so it will be processed by the ApplyResponseGrantAsync method of ExternalCookie. Serialize and encrypt the current identity information and save it to a name. AspNet.ExternalCookie in the cookie and then redirect to AcountController’s ExternalLoginCallback.

4. The ExternalLoginCallback method is actually used for authentication in ASP.NET. The first step is to obtain the authenticated user name and other information from a third party, and then save the user’s information in the form of a cookie to the ExternalCookie. Firstly, the authentication method of ExternalCookie middleware is called by AuthenticationManager to obtain the user information saved in the Cookie. Then, the user information is queried in the local database. If the user exists, the login succeeds. Otherwise, jump to ExternalLoginConfirmation page to add user information (equivalent to complete registration according to the third party user name) after login, user information after a successful login will be save Cookie authentication middleware to active mode. The AspNet. ApplicationCookie. (Note: Refer to the login process of common authentication.)

The above is the execution process of the three authentication processes. Although their processes are different, the final purpose is the same. In each authentication process, the SignIn method of SignInManager is used to complete the login, that is, no matter what method is used to log in, the identity information will be saved in the form of Cookie named. AspNet.ApplicationCookie In the Cookie. And this method clears both the two-factor validation and the external Cookie validation:

  

In addition, as an additional authentication method, two-factor authentication can be attached to both the common authentication method and the third-party authentication method.

summary

This chapter introduces the Owin authentication mechanism and ASP.NET MVC Identity based authentication solution. ASP.NET MVC uses Identity based Owin to provide three authentication methods, which can meet the daily development needs. An understanding of these processes will allow you to better refine your own project’s authentication capabilities based on your requirements. In the next article, I will add two-factor authentication and third-party account authentication to My Blog in the form of code.

PS: People think these processes or more complex, this chapter content is only for general process are introduced, also in the actual code for authentication in other situations that may occur in the processing, interested can look up by way of decompiled corresponding types of source code, in general, ASP.NET provides developers with a very powerful authentication, Do you think that a few lines of code that you’re developing are going to be replicated like this? In addition, thank you for your support to me, if you have any questions, please feel free to put forward, we will make progress together. The next article will show you how to implement third-party account login and two-factor authentication in code. ^_^ (* *)

reference

Bitoftech.net/2015/01/21/… www.cnblogs.com/XiongMaoMen… Stackoverflow.com/questions/2… Docs.microsoft.com/en-us/aspne… www.benday.com/2014/02/25/…

This paper links: www.cnblogs.com/selimsong/p…

ASP.NET has no magic — directories