Asp. NET does not have magic--asp.net authentication and identity

Source: Internet
Author: User

In the previous article for my blog added the article management function (ASP.--asp.net MVC uses area to develop a management module), but the management function should only be accessed by "author", then how to control the user's access rights? That is, when the user accesses the management function needs to authenticate the user, for the user authentication is logged in, that is, to provide a login interface, through the form of an account password can access restricted content.

This article describes how ASP. NET MVC implements user authentication in the following ways:
Authentication in the Web
ASP. NET's identity component introduction
Installing using the identity--component in ASP.
Using Identity--entityframework in ASP. NET MVC
Implementation of using the identity--Registration feature in ASP.
Implementation of using the identity--login feature in ASP.
Implementation of the use of identity--Authentication feature in ASP.

Note: The purpose of this article is to describe how to use the identity component in existing projects to add user registration, login and authentication functions, so the content will be compared trivial, followed by the identity of the more critical points, such as the encryption of the user password decryption, cookie generation and validation, An in-depth analysis of identity and Owin, etc.

Authentication in the Web

Web application as a special application software system, it is based on the HTTP protocol, because of the uniqueness of HTTP (stateless) so each access is independent, do not carry the last request information, so the common authentication method is now used in the form of a cookie or URL query string to save "Status" information to reach the server each time the server can "know" the purpose of the user identity.

Asp. NET as a development framework for a Web application, provides some authentication methods such as from authentication, which generates an encrypted cookie information through user characteristics of the server mentioned by the user (such as user name, password, etc.), and subsequent requests will prove the identity of the user with the cookie information. is the cookie information in the blog park:

  

With the development of software system, the common authentication can not meet the requirements of the system, such as two times authentication, third-party account login, user authorization and so on. Therefore, ASP. NET also developed identity components for these requirements (formerly known as membership).

Asp. NET's identity component introduction

Identity is used to quickly build a sophisticated authentication system for an ASP. It can support all program authentication under the ASP. and EF Code first to support the persistence of user data and integrate Owin to decouple from system.web. It also supports advanced features such as third-party account login, sms/Mail two-time verification, and more.

The main components of the identity are as follows:

The core class library of Microsoft.AspNet.Identity.Core:Identity realizes the core function of authentication and provides the extension interface.
Microsoft.AspNet.Identity.EntityFramework:Identity data persistence for EF implementations.
Microsoft.AspNet.Identity.OWIN: Identity-based OWIN authentication plug-in, which replaces the original form validation.
Microsoft.Owin.Host.SystemWeb:Owin IIS host that transfers the received request for IIS to Owin processing.

Installing using the identity--component in ASP.

1. Install Microsoft.AspNet.Identity.EntityFramework with NuGet (Microsoft.AspNet.Identity.Core included):

  

2. Install Microsoft.AspNet.Identity.OWIN:

  

3. Install Microsoft.Owin.Host.SystemWeb:

  

Using Identity--entityframework in ASP. NET MVC

The above describes the identity support EF Code First, then naturally think of entities and DBContext, then in the identity of how they are implemented?

1. Entities in the identity:

In the case of user information, the Microsoft.AspNet.Identity.Core class library provides the user's core interface:

  

Its implementation is in Microsoft.AspNet.Identity.EntityFramework:

  

In addition to user, the identity defines the entities such as role, Userclaim, Userlogin, and userrole, such as:

  

2. DbContext in the identity:

A identitydbcontext type is provided in Microsoft.AspNet.Identity.EntityFramework (note: The generic implementations of other identitydbcontext are used to extend the entity, If no expansion is required, then non-generic types are used.

  

3. Use the identity-provided dbcontext in the ASP. NET MVC Project (note: Most of the code in this example refers to the ASP. NET MVC Default template code):

1). Inherit the identitydbcontext<tuser> type and implement your own DbContext ( Note: DbContext with identity through inheritance can flexibly change the configuration of DbContext and its entities according to requirements .

    

2). Use the enable-migrations command to enable Automatic migration and set up automatic updating of the database to the latest version of the model in Blogidentitydbcontext:

Automatic migration (that is, you do not need to use the add-migration command to add database structure changes):

    

Automatically update the database to the latest version of the model:

    

Note: This example is based on the MySQL database implementation of my blog, in order to avoid errors when updating the database, so in Onmodelcreating added two objects of the primary key.

    

3). Add the MySQL configuration in Web. config and a connection string called "DefaultConnection" (because the parameter defaultconnection is specified in the DbContext constructor above):

    

Connection string: Share the same database with Blogcontext:

     

Note: Here to illustrate two points, the first is to use the form of configuration files to configure the MySQL configuration of EF because the MyBlog does not reference the EF MySQL components, cannot use the code, and so on after the compilation is completed, all dependent assemblies are copied to the Bin directory, The configuration file is parsed when the program is started. 2nd, there are now two dbcontext introduced throughout the solution, and multiple dbcontext can coexist, as long as they are properly configured and provide the correct connection string. If there is more than one dbcontext in a project, it is necessary to specify the DbContext to be manipulated by the parameters, which can be referenced in this article: http://www.cnblogs.com/Jack-Blog/p/4699596.html

4). You can execute the update-database command to synchronize the DbContext to the database (because automatic database synchronization is set up, so you can also wait for automatic synchronization when the program is run later):

    

    

Implementation of using the identity--Registration feature in ASP.

Before implementing the registration feature in ASP. NET MVC, let's look at the business logic "layer" provided by the identity component (note: "Layer" here is simply to correspond to the existing project structure, there is the data layer and the logic layer, in fact, in the identity of this division, Although they are all in the same assembly).

The identity provides the implementation type of business logic such as RoleManager, Usermanager, and is the definition of Usermanager:

  

As you can see, it already has the implementation of logic such as creating users and adding roles, so it is only necessary to invoke the corresponding method of Usermanager for the registration function. Here's how to add a registration feature:

1. Add the ViewModel used for registration:

  

2. Create the AccountController and register action methods:

  

Note: Usermanager relies on Userstore,userstore and relies on dbcontext, that is, business logic depends on warehousing, warehousing and rely on the implementation of database operations.

3. Create VIEW:

  

4. Include the registration link in the layout page:

  

5. Run:

  

  

Database results:

  

Implementation of using the identity--login feature in ASP.

The purpose of the login function is to verify the user name and password that the user submits to the server, and to generate an encrypted string containing the user information and return it to the client as a Cookie after successful verification. .

The login feature is implemented in the same way as registering a view model, action, and view, and then invoking the identity's user authentication method in action:

1. Create ViewModel:

  

2. Add Login Action (Note: Siginmanager encapsulates the business logic of login including write cookies):

  

3. Add a view and join the login link on the layout page:

  

  

4. Operating effect:

  

  

Note: Access restrictions are not added now, so logging in and not logging in is actually the same.

Implementation of the use of identity--Authentication feature in ASP.

When the user completes the login operation, only one more user information is in the cookie, if the information is not verified then this information is not useful, ASP. NET does not have magic, any of its operations are supported by the code behind, that is used to support identity authentication of the code is? Previously mentioned in the introduction of identity, it is decoupled from the Web server through Owin, Owin it is a Web server processing HTTP request a specification, and it is a httpmodule extension in IIS (about Owin follow-up will be described in detail )。 In general , in IIS, the Owin is expanded to HttpModule, adding a processing pipeline for HTTP request processing .

Then the integration of identity and Owin is actually in the Owin processing pipeline to read the cookie generated after login in the request data and verify that the implementation is as follows:

1. Create a Owin startup class file:

  

2. Add a cookie-validated middleware to the configuration method and automatically jump to the login page when not logged in to access restricted content:

  

3. Add the authorize attribute to the controller that needs to restrict access:

  

4. Add logical judgment in the layout file, display the user name when login is successful, display the login link when not logged in:

  

5. Run:

Access restricted pages Admin/home/index (not logged in will jump):

  

Access to restricted content after login:

  

Login Home page (due to style issues "welcome admin" string with background color (╯-╰)):

  

Summary

The main content of this chapter is a brief introduction to ASP. NET authentication and identity, and then explains how to implement user registration, logon, and authentication through identity in ASP. The code for this example primarily references and simplifies the default ASP. NET MVC with independent authentication template code, so you can compare it against the template code if necessary.

It is also important to note that the registration through the template, login is with model data validation, but this example is not included in the validation of the model will be introduced in the following.

Reference:

http://johnatten.com/2014/04/20/asp-net-mvc-and-identity-2-0-understanding-the-basics/
https://docs.microsoft.com/en-us/aspnet/identity/overview/getting-started/ Adding-aspnet-identity-to-an-empty-or-existing-web-forms-project
https://msdn.microsoft.com/zh-cn/library/azure/ms789031 (v=vs.90). aspx
Http://www.cnblogs.com/dinglang/archive/2012/06/03/2532664.html
Http://www.cnblogs.com/xzwblog/archive/2017/05/10/6834663.html

This article link: http://www.cnblogs.com/selimsong/p/7723827.html

Asp. NET no magic--Directory

Asp. NET does not have magic--asp.net authentication and identity

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.