ASP. NET has no magic -- ASP. NET Identity's "multi-factor" authentication code, asp. netidentity
The previous article introduces the authentication mechanism and process in ASP. NET. This article uses code to introduce how to implement third-party account authentication and two-factor authentication.
This chapter mainly covers:
● Third-party authentication based on Microsoft accounts
● Two-factor authentication
● Verification Code Mechanism
Third-party authentication based on Microsoft accounts
ASP. in the. net mvc template code, the logon codes for Microsoft, Google, twitter, and Facebook accounts are added by default (although Annotated), and corresponding components are provided for some domestic social accounts, all components can be installed through the Nuget Package Manager:
We can see that Youku, QQ, Weibo, and other components are provided by Microsoft, and some are provided by other developers. This document uses a Microsoft account as an example to describe how to implement a third-party login.
NOTE: For the main code in this chapter, refer to the ASP. net mvc template code. Therefore, only key codes are listed in the article. The remaining codes are exactly the same as those in the template.
Component installation and Key application
Before development, install Microsoft. Owin. Security. MicrosoftAccount through Nuget:
In addition, you need to go to the Microsoft Developer Center to use a Microsoft account to create your own application information https://developer.dev.microsoft.com/, and ensure that the application's idleness is used for configuring the ID verification median:
The creation process is as follows:
1. click the Add application button to enter the application registration page, enter the application name, and click the Create button (Note: As I already have an App named My Blog, therefore, the creation process of the Test App is only used for demonstration. The subsequent authentication is actually using the My Blog created previously ):
2. Click Generate new password on the subsequent page to generate the key (note: this password is only displayed once and must be copied and saved in the pop-up box ):
3. add platform: Click the Add platform button to add a Web platform and enter the address for local debugging in the Redirection Url of the Platform (note: you must start HTTPS and add signin-microsoft after the address. VS can enable SSL in the properties of the project and set the ssl url ):
4. Save the changes.
Add Middleware
As described in the previous article, in addition to the specific account authentication middleware, third-party account authentication also requires an external Cookie authentication middleware in the negative mode, first, you need to add the code in the Startup file of the project:
Then add the Microsoft authentication middleware after the middleware (note: the middleware order will affect the processing process, and the Microsoft authentication middleware must be after the external Cookie middleware ), set the Application ID and secret created above:
Add support for Controller and page Functions
Now it can be said that the application already supports Microsoft account authentication, but the entry to Microsoft authentication and the completion of user information after login are not provided in the application.
1. Add a verification entry on the page, add the following code to the Login page, use AuthenticationManager to obtain all third-party authentication methods, and generate the corresponding link:
2. Add the ExternalLogin Action Method to AccountController (Note: The main purpose of this method is to call the Challenge method of AuthenticationManager to trigger the ResponseChallenge method of the Microsoft authentication middleware to redirect the page ):
ChallengeResult is a custom ASP. net mvc Reuslt type:
3. add the callback method ExternalLoginCallback after third-party authentication. The callback method is to obtain the user information after third-party authentication, and then find the user in the local database. If so, the login is successful, otherwise, you need to complete the user information.
4. add the third-party account information completion page and Action method. The action method receives the supplemented user information and completes the user registration function. However, note that the third-party account does not have a password, only third-party authentication information is added to the AspNetUserLogins table:
Running result:
1. The Microsoft button appears on the logon page (Note: You must use an HTTPS address to use Microsoft authentication ):
2. Click "Microsoft authentication" to go To the logon page of the Microsoft account:
3. After the logon is completed, the information completion page will be displayed as this is the first Logon:
After entering the email address, the logon is successful:
Information in the database:
You can see that there is no password, and there is a piece of data in the Login table:
Implement two-factor authentication
Identity two-factor authentication is actually a built-in feature of Identity. Why is it built-in? Because you only need to send information (such as emails and text messages), then perform simple configuration on SignInManager in Identity, and add some pages for sending and entering verification codes. So the first thing to do is to implement the information sending function.
Note: The message sending function is simulated by writing information to the hard disk.
1. Implement information transmission:
The following code is created in the default ASP. net mvc template:
The default email and SMS sender is not implemented, but a null value is returned. Now, the information is written to the hard disk by writing the hard disk:
2. Complete the two-factor authentication configuration of UserManager:
Three key points: 1. TokenProvider, which is used to generate a verification code. 2. Information Format. 3. Information Transmission Service.
3. Add two-factor authentication middleware to the authentication pipeline:
The middleware is used to process secondary verification, while the middleware is used to remember the logon status and automatically log on when you access the system the next time.
4. Select the verification code sending method and enter the verification code page and corresponding Action method (Code omitted ).
5. in the database, change the user information used for the demonstration to enable secondary verification (Note: The template Code has the function for managing personal information, which is omitted here, you can directly modify the data to enable two-factor verification and add phone numbers ):
6. Running result:
After logon, You must select the verification code sending method:
Select and click Submit. When the page is adjusted to the verification page, the required verification code is generated in the specified file:
Enter the verification code and click Submit. The logon is successful:
Note: two-factor authentication can also be applied to third-party Account Login methods. two-factor authentication is only related to the user and the authentication method.
Verification Code Mechanism
For two-factor verification, the verification code is actually sent and verified based on common verification or third-party account verification, how is the Identity of the Verification Code subject maintained?
In the above introduction, one step is to configure UserManager to support message sending and message generation for two-factor authentication:
According to this Code, XXXTokenProvider is used to maintain the verification code, and XXXService is used to send the verification code. Therefore, TokenProvider is described here to understand how the verification code is maintained:
It is a simple class diagram related to TokenProvider. It can be seen from the class diagram that TokenProvider actually implements an interface named IUserTokenProvider. This interface has four methods and their functions are:
● GenerateAsync: generate a Token based on UserManager and User information ).
● IsValidProviderForUserAsync: checks whether the Token provider is valid for this user (if the user uses text message verification but does not set a mobile phone number, it is invalid ).
● NotifyAsync: This method is called to notify users after the Token is generated, such as SMS or email notifications.
● ValidateAsync: used to verify whether the Token is valid.
TotpSecutityStampBasedTokenProvider is a generator that implements the IUserTokenProvider interface and generates the verification code through the user security stamp:
The Code shows that the Algorithm is Based on rfc6238 (TOTP: Time-Based One-Time Password Algorithm, Time-Based One-Time Password Algorithm) round ("D6 ") is to convert it into a 6-digit string.
The Token verification method and generation are similar to the user security stamp and information entropy to verify the submitted verification code (it is actually a hash algorithm ):
The above has explained the issue of generating and verifying the initial verification code. Therefore, for EmailTokenProvider and PhoneNumberTokenProvider, only the entropy is generated and the Provider is valid (whether there is an Email or phone number) the notification method has been modified. The following code is related to PhoneNumberTokenProvider:
Summary
This chapter mainly implements ASP in the form of code. NET third-party authentication and two-factor verification, the code in this article comes from ASP. net mvc template, so this article only introduces the key code, some details can refer to the complete code. Third-party authentication uses a Microsoft account. If you have environment support, you can try domestic authentication, such as QQ.
In addition, at the end of the article, I analyzed the generation and verification code of the Verification Code, knowing that it is implemented based on the Hash algorithm's Information Encryption and verification mechanism.
ASP. net mvc provides comprehensive and powerful user management and Identity authentication functions based on Identity. In addition to the preceding descriptions, it also provides account locking, email registration, and SMS verification functions, it basically covers the common functions currently developed, but these functions are implemented by a template, so ASP. is NET powerful?
Refer:
Https://www.zhihu.com/question/22178202
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/7942513.html
ASP. NET has no magic-directory