A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
ASP. NET has no magic-ASP. NET authentication and Identity, asp. netidentity
In the previous article, I added the article management function (ASP. NET has no magic -- ASP. net mvc uses Area to develop a management module), but the management function should only be accessed by the "author". How should we control the user's access permissions? That is, when a user accesses the management function, authentication is required for the user. For the user, authentication is login, that is, a logon interface is provided, you can access restricted content after logging on with your account and password.
This article describes how ASP. net mvc Implements user identity authentication from the following aspects:
● Web Authentication
● ASP. NET Identity component Introduction
● Install using the Identity component in ASP. NET MVC
● Use Identity -- EntityFramework in ASP. NET MVC
● Implement Identity -- registration in ASP. NET MVC
● Implement Identity-Logon in ASP. NET MVC
● Implement Identity-Authentication in ASP. NET MVC
Note: The purpose of this article is to introduce how to use the Identity component in an existing project to add user registration, login, and authentication functions. Therefore, the content is relatively cumbersome, in the future, we will introduce key points in Identity, such as encryption and decryption of user passwords, Cookie generation and verification, and in-depth analysis on Identity and Owin.Web Authentication
Web applications, as a special application software system, are based on the HTTP protocol. Due to the unique characteristics of HTTP (stateless) therefore, each access request is independent and does not carry the information of the previous request. Currently, common authentication methods are to store the "status" information through cookies or url query strings, each time you access the server, the server can "know" the identity of the user.
ASP. as the development framework of a Web program, NET provides some authentication methods, such as From authentication. It passes the user features (such as the user name and password) of the server mentioned by the user) generate an encrypted Cookie, which will be used in subsequent requests to prove the identity of the user. Is the Cookie information in the blog:
With the development of the software system, ordinary identity authentication cannot meet the requirements of the system, such as secondary authentication during logon, third-party account logon, user authorization, and so on. Therefore, ASP. NET has developed the Identity component (formerly known as MemberShip) to address these needs ).ASP. NET Identity component Introduction
Identity is used to quickly build a complete authentication system for ASP. NET applications. It supports identity authentication for all programs in the ASP. NET Framework, supports user data persistence through EF Code First, and integrates OWIN to decouple systems. Web. It also supports advanced functions such as third-party account logon, text message/Email secondary verification.
The main components of Identity are as follows:
● Microsoft. AspNet. Identity. Core: Core class library of Identity, which implements Core features of Identity authentication and provides extended interfaces.
● Microsoft. AspNet. Identity. EntityFramework: EF Implementation of Identity data persistence.
● Microsoft. AspNet. Identity. OWIN: the Identity-based OWIN authentication plug-in, which replaces the original Form authentication.
● Microsoft. Owin. Host. SystemWeb: the IIS Host OF Owin, which transfers the requests received by IIS to Owin for processing.
1. Install Microsoft. AspNet. Identity. EntityFramework (including Microsoft. AspNet. Identity. Core) through Nuget ):
2. Install Microsoft. AspNet. Identity. OWIN:
3. Install Microsoft. Owin. Host. SystemWeb:
Use Identity -- EntityFramework in ASP. NET MVC
As mentioned above, Identity supports code first of EF, so we will naturally think of entities and DBContext. How are they implemented in Identity?
1. Entities in Identity:
Taking the User information as an example, the Microsoft. AspNet. Identity. Core Class Library provides the Core User interface:
Its specific implementation is in Microsoft. AspNet. Identity. EntityFramework:
In addition to the User, Identity also defines the Role, UserClaim, UserLogin, and UserRole entities, such:
2. DBContext in Identity:
In Microsoft. aspNet. identity. entityFramework provides an IdentityDbContext type (note: the generic implementation of other IdentityDbContext is used to expand the entity. If there is no need for expansion, you can use a non-generic type ).
3. Use the DbContext provided by Identity in the ASP. net mvc Project (NOTE: For most of the Code in this example, refer to the default template code of ASP. net mvc ):
1) inherit the IdentityDbContext <TUser> type to implement your own DbContext (Note: using the DbContext of Identity through inheritance, You can flexibly change the configuration of DbContext and its entities as needed ).
2) use the enable-migrations command to enable automatic migration, and set in BlogIdentityDbContext to automatically update the database to the latest version of the model:
Automatic migration (you do not need to use the add-migration command to add database structure changes ):
Automatically update the database to the latest model version:
Note: This example is based on the MySQL database implementation of My Blog. when updating the database, an error is avoided. Therefore, the OnModelCreating contains the primary keys of two objects.
3) Add the EF configuration of MySQL and a connection string named "DefaultConnection" in web. config (because the DefaultConnection parameter is specified in the DbContext constructor above ):
Connection string: shares the same database with BlogContext:
Note: There are two points to describe here. The first reason is that the MySQL configuration of EF is configured in the form of a configuration file. The reason is that the MySQL component of EF MySQL is not referenced in MyBlog and the Code cannot be used, only after compilation is complete will all dependent assembly be copied to the bin directory, and the configuration file will be parsed when the program is started. The second point is that two dbcontexts are introduced in the entire solution. Multiple dbcontexts can coexist, as long as they are correctly configured and the correct connection string is provided. If a project has multiple DBContext, You need to specify the DbContext to be operated through the parameter for the migration operation, you can refer to this article: http://www.cnblogs.com/Jack-Blog/p/4699596.html
4). You can run the update-database command to synchronize DbContext to the database (because automatic database Synchronization is set, you can also wait for the subsequent automatic synchronization program ):
Implement Identity -- registration in ASP. NET MVC
In ASP. before implementing the registration function in. net mvc, you must first understand the "layer" of the business logic provided by the Identity component. (Note: The "layer" is only used to correspond to the existing project structure, the data layer and logic layer are also divided in Identity, although they are all in the same set of programs ).
Identity provides implementation types of business logic such as RoleManager and UserManager, which is defined by UserManager:
It can be seen that it has implemented logic such as creating users and adding roles. Therefore, for the registration function, you only need to call the corresponding method of UserManager. The following describes how to add the registration function:
1. Add the ViewModel used for registration:
2. Create AccountController and the Register Action method:
Note: UserManager depends on UserStore, and UserStore depends on DbContext. That is to say, the business logic depends on warehousing, and the warehousing depends on the implementation of database operations.
3. Create a View:
4. Add the registration link to the layout page:
Implement Identity-Logon in ASP. NET MVC
The purpose of the login function is to verify the user name and password submitted to the server by the user. After the verification is successful, an encrypted string containing the user information is generated and returned to the client as a Cookie.
The login function implementation method is similar to registration: add View models, actions, and views, and then call the Identity user authentication method in the Action:
1. Create a ViewModel:
2. Add a logon Action (Note: sigInManager encapsulates the login business logic including writing cookies ):
3. Add a View and add a logon link to the layout page:
4. Running effect:
Note: access restrictions have not yet been added, so logon and non-Logon are actually the same.Implement Identity-Authentication in ASP. NET MVC
After the user completes the login operation, only one user information is added to the Cookie. If the information is not verified, this information does not work. ASP. NET has no magic, and any of its operations are supported by code. What is the code used to support Identity authentication? I mentioned earlier that Identity is decoupled from Web Servers through Owin, which is a specification for Web servers to process HTTP requests, it is an httpModule extension in IIS (for details about Owin later ). In general, the Owin in IIS adds a processing pipeline for HTTP request processing in the extended way of HttpModule.
Therefore, the integration of Identity and Owin is actually in the Owin processing pipeline to read and verify the Cookie generated after login in the request data. The implementation is as follows:
1. Create an Owin Startup class file:
2. Add the middleware for Cookie verification in the Configuration method. When the access restriction is not logged on, the logon page is automatically displayed:
3. Add the Authorize feature to the Controller to restrict access:
4. Add logic judgment to the layout file. The user name is displayed after logon is successful, and the logon link is displayed when logon is not successful:
Admin/home/index on the restricted access page (skip if you are not logged on ):
After logging on, you can access restricted content:
After logging on to the homepage (due to style issues, the "Welcome admin" string is in the same color as the background (character □background )):
This chapter focuses on ASP. NET Identity authentication and Identity are briefly introduced, and then explained in ASP.. net mvc Implements user registration, logon, and Identity Authentication through Identity. The code in this example mainly refers to and simplifies the default ASP. net mvc template code with independent authentication, so you can compare it with the template code if necessary.
In addition, registration and login created through the template all carry model data verification, but this example is not included. model verification will be introduced later.
Https://msdn.microsoft.com/zh-cn/library/azure/ms789031 (v = vs.90). aspx
ASP. NET has no magic-directory
Start building with 50+ products and up to 12 months usage for Elastic Compute Service