ASP. NET has no magic-"multiple" authentication for ASP. NET Identity, asp. netidentity
ASP. in addition to Cookie-based Identity authentication, NET Identity also provides some advanced functions, if the incorrect account information is entered multiple times, the user is locked for login prohibited, third-party authentication is integrated, and the account is verified twice, and ASP. net mvc default templates include these functions.
This article explains how ASP. NET Identity implements the Identity authentication mechanism from the following aspects:
● "Multiple" authentication for ASP. NET Identity
● Active and passive modes of Owin Identity Authentication
● Talking about the Owin authentication mechanism
● Owin-based Identity Authentication solution in ASP. NET
"Multiple" authentication for ASP. NET Identity
Why does this chapter refer to Identity multi-factor authentication? Because ASP. NET Identity is implemented through Middleware Based on Owin, the following code is added in the default template:
From the code, we can see that the template Code adds a total of seven (including three Annotated) Authentication-related middleware, according to the understanding of Owin middleware, when a request enters the Owin pipeline, each middleware will be executed. The authentication middleware above is divided by function.Cookie-basedYesExternal Cookie-based,Two-factor verificationAndThird-party Account Login(Annotated Code), which means that each request is processed by these middleware one by one, so it is called "multiple" authentication.
From the title to the present, "multiple" are all quoted, indicating that authentication in Identity is not as simple as Multiple Functional stacks on the surface. Next we will start from the AuthenticationPositive ModeAndNegative ModeTo eliminate the fog of Identity in ASP. NET authentication.
Positive and Negative modes of Owin Authentication
Identity is based on Owin for Identity authentication. In fact, Owin is the rule maker for Identity authentication. Identity is only one implementation. In Owin, authentication middleware is divided into two modes, the two modes are the positive mode and the negative mode. The two modes are defined by an enumeration type named AuthenticationMode:
According to the Code annotations, we can introduce the positive and negative modes as follows:
● Active: the Active authentication middleware modifies the user's identity information when the request arrives, and processes the response information when the response status is 401.
● Passive mode: only the middleware in this mode needs to or explicitly call the middleware to verify the request, this includes that when 401 occurs, the corresponding verification type name needs to be found in the expanded Challenge data for processing.
In a wordNo matter how many authentication middleware is added to the Owin pipeline, requests are processed only when the Authentication mode is positive. Others must be called manually.. Why? See the following content.
Talking about Owin authentication mechanism
The previous article introduced how Owin and Identity are integrated, such as ASP. NET has no magic-Identity and Owin, ASP. NET has no magic -- ASP. NET Identity encryption and decryption, however, it mainly introduces how Identity is added to the Owin pipeline through middleware to verify user Identity information and what work is done by the Cookie-based authentication middleware. The core point is not mentioned yet, that is, the Identity authentication mechanism or rules are determined by Owin (Katana). Identity is only an implementation that follows this rule and can even be said to be a user, because it only provides user data for the Cookie authentication middleware, and then relies on AuthenticationManager to implement and expand ASP.. NET.
The above is the Owin authentication package diagram, from which you can draw the following conclusions:
1. Micrsosft. Owin defines Owin-related subjects such as context, pipeline Builder, andAuthentication-related business logic AuthenticationManager.
2. Microsoft. Owin. Security as OwinSecurity-related functionsDefines the Authentication Mode (positive and negative) as well as the middleware and processor base classes for identity authentication.
3. Microsoft. Owin. Security. XXX typeReal Identity Authentication logic implementerProvides various Cookie-based, Token-based, and third-party account authentication logic.
4. microsoft. aspNet. identity. owin has two main objects: SignInManager encapsulates the business logic during logon. This business logic includes the user data operation (UserManager) and Identity Authentication logic, provides advanced functions such as Common Logon, two-factor logon, and external account logon. AuthenticationManagerExtensions is also an extension of AuthenticationManager for these advanced functions.
AuthenticationManager
AuthenticationManager is the core of authentication in Owin. Its interface is defined as follows:
According to the notes, it is usedInteracts with the authentication middleware connected to the pipelineIn addition, AuthenticateAsync and Challenge are provided for identity authentication (I will translate them into denial or question). In other words, the authentication fails) log on to SignIn, log out of SignOut, and obtain the authentication method GetAuthenticationTypes.
AuthenticationManager can be understood in this way. Each request creates an AuthenticationManager that carries the User information of the current request, and then manages all authentication middleware connected to the Owin pipeline, through this series of middleware, user authentication and rejection, login and logout are completed.
It should be noted that the AuthenticateAsync returns a verification result that contains user information in addition to the verification result, while the SignIn method actually adds or replaces user information) the user information of the current request context. In most cases, the AuthenticateAsync and SignIn methods are continuously used.
AuthenticationMiddleware & AuthenticationHandler
As template code, AuthenticationMiddleware and AuthenticationHandler restrict the execution of middleware and the processing method of the processor:
How to execute AuthenticationMiddleware:
There are four stages: 1. The creation of the processor. 2. initialize the processor. 3. Call of the processor. 4. Destroy the processor.
For AuthenticationHandler, there are several important processes:
1. Initialization: register the current processor to AuthenticationManager. If the current middleware mode is positive, the authentication method is called. Otherwise, the authentication method can only be called through AuthenticationManager. (Note: The specific implementation of InitializeCoreAsync is in the subclass)
2. Execute:
From the above analysis, we can know that there is an authentication method AuthenticateAsync in the authentication process. What is the purpose of the execution method? In the Identity-based ASP. in the. NET application, the authentication method automatically authenticates requests only in active mode, in addition, requests are not processed regardless of whether they pass authentication (even if they do not pass authentication, requests can still be sent to the Controller or Action for execution because they can be called anonymously ), however, when the server processes a request, it can determine how the request should be handled. For example, after logging on to a third-party account, the server will carry some tokens and other information on the Url query string, at this time, we can determine that we need to process the information to complete identity authentication, rather than sending the request to the Controler for processing, in this case, the processing logic can be put into the Invoke method. If the Invoke method returns true, the pipeline will not continue to execute (see the Invoke method of middleware ). During social account verification such as Microsoft and Google, the verification logic is written in this InvokeAsync method, and the middleware for Cookie verification returns false by default to deliver the request to the subsequent component for processing, the third-party verification of Owin will be detailed later.
3. destruction: when a request is in the return stage, the destruction process of the authentication processor is triggered, the entire process includes writing the identity information into the response information (for example, Cookie verification will serialize and encrypt the AuthenticationTicket object and write it into the Cookie), and executing some destruction logic of the subclass, delete the processor added to AuthenticationManager.
SignInManager & AuthenticationManagerExtensions
SignInManager is used to manage user logon logic, such as logon, Password Logon, two-factor logon, and external logon. It encapsulates UserManager and AuthenticationManager:
AuthenticationManagerExtensions is an extension of AuthenticationManager. It mainly adds external verification and two-factor verification support to AuthenticationManager. These extension methods are used by SignInManager and the authentication Controller:
Owin-based Identity Authentication solution in ASP. NET
The main components and functions of Owin and Identity are introduced above. How can I use these functions in ASP. NET to implement Identity authentication? In ASP. NET, identity authentication is divided into three types:
● Common authentication: common authentication is the Cookie-based authentication method described in the previous article. The process is that the user submits the user name and password, and the server generates the user information after the password is verified, subsequent requests can verify the user identity based on the user information.
● Two-factor verification: two-factor verification adds secondary verification of information such as SMS verification code and email Verification Code on the basis of common verification, that is, after the server completes user verification based on the user name and password, the user is still in the "not passed" authentication status, and the verification code sent to the customer must be verified twice before the authentication is completed.
● External verification: After user data is logged on to the application, such as different social accounts, through the authentication interfaces provided by these service providers, returns a series of verification methods for service access Token and user information.
Here we will introduce how the above three methods are implemented using the Identity component through the template code with the authentication function of ASP. net mvc.
Common Verification
Identity in ASP. NET implements normal user identity authentication through Cookie authentication. The main process is as follows (Note: The left side is the main process, and the right side is the sub-process included in each main process ):
In ASP. net mvc, Identity is used to generate user information for Cookie-based user Identity authentication. There are several points to note:
1. first, the user name, password, and other information are submitted to the server through the Login method in AccountControllter that can be accessed anonymously. Then, the user name and password are verified and logged on through PasswordSignInAsync of SignInManager, finally, the user identity information is encrypted and written to the Cookie in the request return stage.
2. in the password verification/logon phase, in addition to user password verification, there are also some user locks, Logon Failure count, reset, and other judgments, it is used to implement user locking and automatic user locking for multiple logon failures.
3. signInManager. based on the configuration of the verification method, the SignInOrTwoFactor method determines whether it is a two-factor verification or a common verification, you can obtain the user identity information and create an identity authentication attribute to complete subsequent login operations on the Authentication Manager (Note: As mentioned above, the AuthenticateAsync and SignIn methods are continuously used. The former obtains user information and the latter writes user information to the request context, however, because the current logon operation does not contain user identity information in the request, the user identity information and authentication attributes need to be created by yourself, for example, obtained through the database, here, we use the user information we created and call the SignIn method to write the user information to the request context.).
4. When the request returns, the user information written to the request context is carried to the client in the form of a Cookie for subsequent request authentication.
It is the authentication process when the user accesses other resources after logging on. The entire process is completed by the Cookie verification middleware. The following points must be noted:
1. Cookie verification middleware uses the active mode by default. Therefore, the AuthenticateAsync method will be called during processor initialization to parse and verify the identity information cookies in the request.
2. After Authentication of identity information is completed, the middleware uses the AddUserIdentity method to write user information to the request context (this method actually replaces the SignIn method of AuthenticationManager ).
3. when the request is returned, if the status is normal, the identity information will continue to be written to the Cookie, but if the authentication fails (such as timeout ), the request is processed back by the processor's ApplyResponseChallengeAsync (for example, jump to the login page and other functions ).
Two-factor verification
Two-factor verification introduces the second verification on the basis of common verification, that is, there will be two requests during login:
It is a two-factor verification process. In fact, two-factor verification is based on common verification. It is only enabled through configuration. The verification code sending and verification process is added to the authentication process, note the following points:
1. when you log on for the first time and perform common verification, You need to verify the user password, whether it is locked, and other information. Then, because two-factor verification is required, therefore, a TwoFactorCookie ID is created and the SignIn method of the manager is executed. The password-verified username is saved. After the request is completed, the app. the UseTwoFactorSignInCookie method adds the Cookie authentication middleware to write the TwoFactorCookie ID information created above to the Cookie (Note: Multiple cookies are added to the authentication middleware in the pipeline, however, its configuration and authentication types are different. Here, we choose which middleware is used to process and generate cookies Based on the authentication method of user information, claimsIdentity constructs the passed value as the authentication method ).
2. ASP. the net mvc program redirects the request that completes the first verification to the Verification Code sending (select the sending method) and the verification code filling page, fills in the verification code and submits the verification code to enter the second verification.
3. in the second verification process, the VerifyCode method of AccountController is verified by the TwoFactorSignInAsync method of SignInManager. The core of this method is to explicitly call the "TwoFactorCookie" verification by AuthenticationManager, the verification is app. useTwoFactorSignInCookie method adds a passive mode of authentication middleware. (Note: The constant value of TwoFactorCookie is TwoFactorCookie. The SignIn method of AuthenticationManager finds and calls the corresponding authentication method through string matching)
This verification method is to obtain the last stored Cookie and obtain the username after decryption. After obtaining the user information, verify the verification code using UserTokenProvider. After all the information passes the verification, the AuthenticationManager SignIn method will be used to add user information to the request context (Note: Verification Code Generation and verification will be described in subsequent sections ).
4. When the VerifyCode request responds, the user information is written to the Cookie through the Cookie middleware in the active mode. This process is consistent with the normal verification.
Note: subsequent requests are the same as normal authentication. Use the identity information carried by cookies to complete authentication through the active mode Cookie authentication middleware.
External verification
External authentication transfers the user's authentication process to external servers (such as major social platforms). Compared with the above two verification processes, the external authentication process is more complex, the flowchart is as follows:
(Note: Because the flow chart is too large, it is divided into two parts: the first part is the redirection of the third-party login page, and the second part is the ASP. NET authentication process that is redirected back after the third-party login is completed)
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 AccountController, first, select a third-party account logon method on the page. After the method is submitted to the server, the ExternalLogin method directly rejects the current request through the AuthencationManager's Challenge method, redirect requests to the third-party logon page.
After successful third-party login, The ExternalLoginCallback of AccountController will be reset. The entire process is described as follows:
1. the first thing to mention is that the template project passes the app in the authentication pipeline. the UseExternalSignInCookie method sets the default logon authentication method (ExternalCookie) and adds a negative Cookie authentication middleware. The authentication method is also ExternalCookie.
2. because the request carries information that is verified by Microsoft (Taking Microsoft as an example here), it will be processed by the Invoke method of the specific authentication middleware, the process is to call the corresponding authentication method to obtain the identity information, and add the authenticated identity information to the default authentication type (Note: The default type is ExternalCookie, the purpose is to process all accounts that have passed third-party authentication), write the identity information to the context using the SignIn method, and return True (Note: As mentioned above, when the Invoke method of the authentication processor returns true, subsequent content will not be called ).
3. in the process of returning from the Microsoft authentication processing middleware, because the Authentication Mode of user information in the context is ExternalCookie, it will be processed by the ApplyResponseGrantAsync method of the middleware ExternalCookie, serialize and encrypt the current identity information and save it to the name. aspNet. in the cookie of the ExternalCookie, and then redirects to the ExternalLoginCallback of the AcountController.
4. the ExternalLoginCallback method is actually ASP.. NET. The previous step is to obtain the authenticated user name and other information through a third party, and then save the user information to the ExternalCookie in the form of a cookie, the authentication method of ExternalCookie middleware is called through AuthenticationManager to obtain the user information stored in the Cookie, and then query the user information in the local database. If the user exists, otherwise, log on to the ExternalLoginConfirmation page to supplement the user information (equivalent to completing registration based on a third-party user name). After Successful Logon, the user information will be saved to the Cookie authentication middleware in the active mode. aspNet. applicationCookie. (Note: For details about the logon process, refer to the logon process of common authentication ).
The above are the three authentication processes. Although the processes are different, the final purpose is the same. In each authentication process, logon is completed through the SignIn method of SignInManager, that is, no matter how you log on, the identity information will be saved in the form of a Cookie in the name. aspNet. applicationCookie. In addition, this method clears the information of two-factor authentication and external Cookie authentication:
In addition, two-factor verification is used as an additional verification method, which can be attached to both common and third-party verification methods.
Summary
This chapter describes the authentication mechanism for Owin and ASP. net mvc Identity-based authentication solution is introduced, ASP. net mvc uses the three authentication methods provided by Identity based on Owin to meet daily development requirements. The understanding of these processes can better improve the Identity authentication function in their own projects according to requirements, in the next article, we will add two-factor verification and third-party Account Verification in the form of code in My Blog.
PS: I personally think these processes are complicated. This chapter only introduces the general process and processes other possible situations in identity authentication in actual code, if you are interested, you can view the source code of the corresponding type through decompilation. In general, ASP. NET provides a powerful authentication function for developers. Do developers think that the functions implemented by a few code statements will be copied in this way? In addition, I would like to thank you for your support. If you have any questions, you can make common progress. The next article describes how to implement third-party account logon and two-factor verification using code. (* ^_^ *)
Reference
Http://bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/
Https://www.cnblogs.com/XiongMaoMengNan/p/6785155.html
Https://stackoverflow.com/questions/26166826/usecookieauthentication-vs-useexternalsignincookie
Https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/external-authentication-services
Https://www.benday.com/2014/02/25/walkthrough-asp-net-mvc-identity-with-microsoft-account-authentication/
Link: http://www.cnblogs.com/selimsong/p/7903718.html
ASP. NET has no magic-directory