ASP. net mvc recording-exploring ASP. NET Identity authentication and role-based authorization, mvcidentity
In the previous article, I introduced the use of basic ASP. NET Identity APIs and created several user accounts. In this article, I will continue ASP. the NET Identity tour shows you how to use ASP.. NET Identity Authentication and ASP. net mvc Role-Based Authorization ).
In this example, you can download and preview:
Click here to preview
Click here to download the sample code
Explore identity authentication and authorization
In this section, I will describe and prove the working principles and operating mechanisms of ASP. NET authentication and authorization, and then introduce how to use Katana Middleware and ASP. NET Identity for authentication.
1. Understand ASP. NET form authentication and authorization mechanisms
When talking about identity Authentication, we may be most exposed to Form Authentication ). To better understand ASP. NET form authentication and authorization mechanism. I moved out of an old figure a few years ago, indicating that 19 events of HttpApplication were registered in HttpModule, which is also called ASP.. NET Pipeline (Pipeline) event. In general, when requests arrive at the server, ASP. NET will trigger these events in sequence:
The user-provided Credentials is used for identity authentication ). Once the verification is passed, a unique Cookie ID is generated and output to the browser. The next request from the browser will contain this Cookie, which is well known for ASP. NET applications.FormsAuthenticationModulePipeline event of HttpApplicationAuthenticateRequestWhen the request passes ASP. NET Pipeline, by ASP. NET Runtime triggers it. In this event, it verifies and resolves the Cookie as the corresponding user object, which is an object that implements the IPrincipal interface.PostAuthenticateRequestEvent inAuthenticateRequestThe event is triggered, indicating that the user identity check has been completed. After the check, the user can passHttpContextOfUserProperty andHttpContext. User. Identity. IsAuthenticatedThe property is True.
If you think of identity verification as "opening the door", the host invites you into the room, but this does not mean you can enter the bedroom or study, maybe your activity space is limited to study-this is authorization. InPostAuthenticateRequestAfter an event is triggeredAuthorizeRequestEvent.UrlAuthorizationModuleYou can register the URL module and the FormsAuthenticationModule mentioned above at the IIS level. in the config file. This is also ASP. NET and IIS ). In this event, the request URL is based on the web. the authorization configuration node in config is authorized. As shown below, grant Kim and all roles as Administrator members access permissions and deny access by John and anonymous users.
Through authentication and authorization, We can restrict access to areas sensitive to applications, which ensures data security.
2. Use Katana for authentication
So far, you may have a basic understanding of OWIN, Katana, and Middleware. If you are not clear about it, please go here.
With Katana, you can select several different types of authentication methods. We can install the following types of authentication through Nuget:
- Form Authentication
- Social Identity Authentication (Twitter, Facebook, Google, Microsoft Account ...)
- Windows Azure
- Active Directory
- OpenID
Form authentication is the most widely used. As mentioned above, Form authentication of traditional ASP. net mvc and Web FormFormsAuthenticationModuleWhile Katana overrides Form authentication, it is necessary to compare the differences between Form authentication in traditional ASP. net mvc & Web Form and Form authentication in OWIN:
Features |
ASP. net mvc & Web Form Authentication |
OWIN Form Authentication |
Cookie Authentication |
√ |
√ |
Cookieless Authentication |
√ |
× |
Expiration |
√ |
√ |
Sliding Expiration |
√ |
√ |
Token Protection |
√ |
√ |
Claims Support |
× |
√ |
Unauthorized Redirection |
√ |
√ |
From the comparison above, we can see that Katana has almost implemented all the functions of traditional form identity authentication. How can we use it? Is it still specified in web. config like the traditional one?
If not, Katana completely abandons the FormsAuthenticationModule. In fact, it uses Middleware to implement identity authentication. By default, Middleware performs chained execution when the PreRequestHandlerExecute event of HttpApplication is triggered. Of course, we can also specify it for execution at a specific stage by usingUseStageMarkerIn the AuthenticateRequest stage, we can perform Middleware for authentication.
So how can we implement it? Fortunately, Katana has helped us encapsulate an extension method, as shown below,
App. UseCookieAuthentication is an extension method, which internally helps us with the following:
- Use the app. Use (typeof (CookieAuthenticationMiddleware), app, options) method to register CookieAuthenticationMiddleware to OWIN Pipeline.
- Use the app. UseStageMarker (PipelineStage. Authenticate) method to specify CookieAuthenticationMiddleware to be executed in the AuthenticateRequest stage of the ASP. NET integration pipeline (ASP. NET integrated pipeline ).
When this Middleware is called (Invoke), The CreateHandler method is called to return the CookieAuthenticationHandler object, which contains the AuthenticateCoreAsync method. In this method, the Cookie is read and verified, create the ClaimsPrincipal object using AddUserIdentity and add it to the Owin environment dictionary. You can use the OwinContext Object Request. the User can obtain the current User.
This is a typical use case of Middleware. To put it bluntly, it processes Http requests and stores the data in the OWIN environment dictionary for transmission. What CookieAuthenticationMiddleware does is similar to what FormsAuthenticationModule does.
How can we generate cookies? ASP. NET Identity is used for Identity authentication. If the authentication succeeds, the Cookie is generated and output to the client browser. This closed loop is formed and will be implemented in the next section.
3. Use the Authorize feature for authorization
ASP. NET Identity has been integrated into ASP. NET Framework. In ASP. net mvc, we can use the Authorize feature for authorization, as shown in the following code:
In the code above, the Index Action has been set to restricted access and can be accessed only when the authentication passes. If the authentication fails, the system returns 401.0-Unauthorized, the request is then processed by OWIN Authentication Middleware in the EndRequest stage, and 302 is redirected to/Account/Login.
Use ASP. NET Identity Authentication
Now that you have a basic understanding of Identity authentication and authorization mechanisms, you should use ASP. NET Identity for Identity authentication.
1. Preparations for implementing Identity Authentication
When we access the authorized resources anonymously, it will be Redirect to/Account/Login. The URL structure is as follows:
Http: // localhost: 60533/Account/Login? ReturnUrl = % 2 Fhome % 2 Findex
Because you need to log on, you can set Login to allow anonymous Login. You only need to add[AllowAnonymous]Feature labels are as follows:
Note: Here I have stored the ReturnUrl. As the name suggests, the ReturnUrl is redirected to the original address after successful logon, which improves the user experience.
Due to space limitations, Login View does not post the Code. In fact, it is also very simple and contains the following content:
- Username text box
- Password box
- Store hidden fields of ReturnUrl
- @ Html. AntiForgeryToken (), used to prevent cross-site Request Forgery of CSRF
2. Add a user and implement authentication
After the creden are input, the POST Form is written to/Account/Login. The Code is as follows:
In the above Code, first use ASP.. NET Identity to verify user creden. This is achieved through the FindAsync method of the AppUserManager object. If you do not know ASP. NET Identity basic API, please refer to my article.
The FindAsync method accepts two parameters: the user name and password. If the user name and password are found, the AppUser object is returned. Otherwise, NULL is returned.
If the FindAsync method returns the AppUser object, the next step is to create a Cookie and output it to the client browser, so that the next request of the browser will carry the Cookie. When the request passes the AuthenticateRequest stage, read and parse cookies. That is to say, the Cookie is our token. If the Cookie is like me, we do not have to verify the user name and password.
Using ASP. NET Identity to generate a Cookie is actually very simple. There are three lines of code, as shown below:
The code is analyzed. The first step is to createClaimsIdentityObject, ClaimsIndentity is a class in ASP. NET Identity, which implements the IIdentity interface.
The ClaimsIdentity object is actually created by the CreateIdentityAsync method of the AppUserManager object. It must accept an AppUser object and the authentication type. Select ApplicationCookie here.
Next, let the existing cookies expire and generate new cookies. I have pre-defined an AuthManager attribute, which is an IAuthenticationManager object and used for some common authentication operations. It includes the following important operations:
- SignIn (options, identity) is used to generate a Cookie after authentication.
- The SignOut () log out by name to invalidate the existing Cookie.
SignIn requires two parameters: the AuthenticationProperties object and the ClaimsIdentity object. AuthticationProperties has many attributes. Here I only set IsPersistent = true, which means that the Authentication Session is persistently saved. When a new Session is enabled, the user does not have to verify it again.
Finally, redirect to ReturnUrl:
Use roles for authorization
In the previous section, the Authorize feature is used to restrict access to a specified region. access can be continued only after the authentication is passed. In this section, more fine-grained authorization operations are performed. In ASP. net mvc Framework, Authorize usually performs smaller-granularity authorization operations based on the User or Role attributes, as shown in the following code:
1. Use ASP. NET Identity to Manage Roles
After having a basic understanding of Authorize, we will focus on the management of Role. ASP. NET Identity provides a strong type base class named RoleManager <T> for accessing and managing roles, where T implements the IRole interface, the IRole Interface contains the most basic fields (Id and Name) of the persistent Role ).
Entity Framework provides a class named IdentityRole, which implements the IRole interface. Therefore, it not only contains the Id and Name attributes, but also adds a set attribute Users. IdentityRole has the following important attributes:
Id |
Defines the unique Role Id. |
Name |
Defines the Role name. |
Users |
Returns all Role members. |
I don't want to use IdentityRole directly in the application, because we may want to extend other fields, so we define a class named AppRole, just like AppUser, which inherits from IdentityRole:
At the same time, define an AppRoleManager class. Like AppUserManager, It inherits the RoleManager <T> and provides the basic methods for searching and persisting the Role:
Finally, do not forget to initialize the instance in the OWIN Startup class, which will be stored in the OWIN context dictionary and run through every HTTP request:
2. Create and delete roles
Using ASP. NET Identity to Create and Delete roles is simple. You can obtain AppRoleManager from the OWIN context and Create or Delete the role, as shown below:
3. Manage the role MemberShip
To authorize a user, in addition to creating and deleting a role, you also need to manage the role's MemberShip. That is, you can Add or delete a role to the user through the Add/Remove operation.
To this end, I have added two viewmodels, RoleEditModel and RoleModificationModel, which represent the fields passed to the background during field editing and form Post:
When editing a Role, you can obtain all the members that belong to the Role and non-members that belong to the Role:
The final view is as follows:
When you click Save and submit a form, you can bind the model to Post the data to the Edit Action to manage the role's MemberShip, that is, you can use the Add/Remove operation, you can add or delete roles to users.
, As shown below:
In the above Code, you may notice the UserManager class, which contains several role-related operation methods:
AddToRoleAsync (string userId, string role) |
Add a user to a specified role |
GetRolesAsync (string userId) |
Obtains the role list corresponding to a User. |
IsInRoleAsync (string userId, string role) |
Determine whether a user belongs to a specified role |
RemoveFromRoleAsync (string userId, string role) |
Remove a user from a specified role |
Initialize data, Seeding Database
In the previous section, use the Authorize label to restrict access to the Role controller. Only users with Role = Administrator can access and operate the Role controller.
However, when our applications are deployed in the new environment, there is no specific user data, which makes it impossible for us to access Role Controller. This is a typical "chicken or egg" problem.
To solve this problem, we usually have a built-in Administrator role in the database, which is also a well-known super administrator role. With Entity Framework Seed, we can easily initialize data:
The AppUserManager and AppRoleManager instances are instantiated here, because the PerformInitialSetup method is executed before the OWIN configuration.
Summary
In this article, we explored the use of ASP. NET Identity for Identity authentication and the combination of ASP. net mvc role-based authorization. Finally, role management is implemented. In the next article, we will continue the ASP. NET Identity journey and explore advanced ASP. NET Identity applications-declarative authorization.