Most of us now turn to ASP. NET core to use the development team, should not start from 0 to build the system, but the old business system is already running, ASP. NET core is used to develop new modules. Then solve the user authentication problem, become our first obstacle. This article will give you a brief description of the basic concepts of authentication and authorization, as well as the implementation of the authentication and transformation based on the ASP. Jwtbearer Certification Middleware to achieve the integration with the old system (mainly token-based authentication).
Directory
- Certifications and authorizations
- What is certification
- What is authorization
- Intercept with middleware.
- Custom JWT Bearer Certification
- Change Token source
- Change Token authentication method
- Start authorization
Certifications and authorizationsWhat is certification? first, authentication is not a login. Authentication is a process of knowing who the user is. We first used the session-based authentication, get the user entered the user name and password into the database check one, to see if it is correct, if it is correct we put in the session. This is a complete certification process, the system now know that you are one of my users. So what is authorization? now that the user is logged in, we jump to another page, and this page might write a code like this.
if (session["user"]==null) { Response.Redirect ("/ Login.aspx")}
if the user login session does not exist, then jump back to the login page to let the user log in. This process of checking that the current user has no permissions is called authorization. What if not? We will jump the user to a prompt page without permission, or return the HTTP status code of Forbidden 403, which is the simplest authorization. complex licensing methods include the authorization of roles, access to specific resources, and operations, which we'll talk about later. when our ASP. NET core project needs to be compatible with older projects, it needs to be compatible with the old project's authentication methods, such as some custom tokens (which is a common practice before). We need to determine whether a legitimate user is based on the token in the current user header in ASP. Intercept with middleware.the first simple and rude method is to intercept with middleware. Under ASP. NET Core, MVC joins an entire HTTP pipeline with a middleware. A routing middleware is added before this, which means that routing is no longer part of the same as ASP. On the contrary, there is a mvcroutehandler in the ASP. NET core that is loaded by Routing middleware to handle the request. About routing this piece we'll talk about later. If we're going to do it in MVC middleware, just add a middleware before MVC middleware or routing.
Public voidConfigure (Iapplicationbuilder app) {app. Use (Async(context, next) = { if(Context. Request.Headers.ContainsKey ("token")) { vartoken =context. request.headers["token"]. FirstOrDefault (); if(token = ="jessetalk.cn") { awaitnext (); }} context. Response.statuscode=401; }); App. Usemvc ();}
Above is a middleware that we have an easy way to implement, before being added to MVC. When the request's headers does not have a value of "jessetalk.cn" and an entry with the name "token", we return to the 401 state and do not perform the subsequent processing. (Do not call the next method)but this approach is equivalent to fits, and the middleware that we added took place before the MVC middleware all the requests without authentication information were intercepted. The advantage is that there is a need to conserve server resources (if it is determined that the interception is not necessary to be processed by MVC), the disadvantage is that a single controller or action can not be configured flexibly. Custom Jwtbearer Authentication
The ASP. NET core implements the Jwtbearer authentication for us, and the implementation of Jwtbearer authentication can be referenced in another article, "Using Jwtbearer in ASP. Authentication ". What we are going to do today is to get it to read our custom tokens and verify the token in our own way by customizing the Jwtbearer authentication. It's a bit of a backwards feeling, isn't it?
If both the time and the staff are sufficient, we are likely to replace the standard JWT scheme with a direct whole, or even do sso. However, there is no end to the architecture, in a certain time frame, to achieve efficient and safe switching, this is a good way.
First we need to look at the default token obtained in Jwtbearer is in authorization's head, bearer space plus token. If there is an irregular practice, it is possible to add a token directly inside the headers, which has a token generated using our own algorithm.
Change the origin of tokens
Jwtbearer Authentication Handler provides a onmessagereceived delegate in events that allows us to read tokens from another place.
Services. Addauthentication (options ={options. Defaultauthenticatescheme=Jwtbearerdefaults.authenticationscheme; Options. Defaultchallengescheme=Jwtbearerdefaults.authenticationscheme;}). Addjwtbearer (o={o.events=Newjwtbearerevents () {onmessagereceived= Context = { vartoken = context. request.headers["token"]; Context. Token=token. FirstOrDefault (); returnTask.completedtask; }, };});
How to verify Custom tokens
After getting token from headers, the next step is to change its validation algorithm to our own. This step can be achieved by customizing the isecuritytokenvalidator. We are in this validator, check token generates a Claimsprincipal, this principal will be assigned to HttpContext.User.
We also added a role Claim based on the current token, which has a value of user and admin. This may be used to perform role-based authorization.
Public classmytokenvalidator:isecuritytokenvalidator{ PublicClaimsPrincipal Validatetoken (stringSecurityToken, Tokenvalidationparameters Validationparameters, outSecurityToken Validatedtoken) {Validatedtoken=NULL; varIdentity =Newclaimsidentity (Jwtbearerdefaults.authenticationscheme); Identity. Addclaim (NewClaim ("name","Jesse")); Identity. Addclaim (NewClaim (claimsidentity.defaultroleclaimtype, SecurityToken = ="jessetalk.cn"?"Admin":"User")); varPrincipal =NewClaimsPrincipal (identity); returnprincipal; }}
Note that the authenticationscheme of claimsidentity must be the same as the name we set at Useauthentication. Otherwise the identity.isauthenticated cannot be set to true correctly, and our authorization will not be completed.
With our custom validator, we want to transform Jwtbearer, remove its default validator, and add this to our own definition.
Services. Addauthentication (Options = jwtbearerdefaults.authenticationscheme; == = ={ o.securitytokenvalidators.clear (); O.securitytokenvalidators.add (new mytokenvalidator ());});
Get started with authorization
In order to show you the above function, we create two controller, one is admin, the other is home. Both require the user to have token to normal access, but for the admin we need the user to have the role of admin can, otherwise it will be refused to return 403.
HomeController.cs
[Authorize] Public class homecontroller:controller{ public iactionresult Index () { return Ok (); }}
When there is no token value inside the headers, the API request returns 401.
The API can be accessed normally when there is a token value inside the headers.
We added a admincontroller, not the same is this time we give authorize added role= "admin", that is, only the role of the admin can access the API.
[Authorize (Roles ="admin")] Public class admincontroller:controller{ public iactionresult Index () { return Ok (); }}
When we use User token access, we get 403.
Only use the admin token to access it normally. To be a basic idea of our own certification scheme based on JWT authentication, mainly to implement onmessagereceived to transform the source of tokens and define your own
ISecurityTokenValidator
To implement token validation. This article is starting with the public number Jessetalk. If you want to reprint, please keep the public number QR code, thank you. More great articles: ASP. NET core Dependency Injection all know: http://dwz.cn/6QEcm2 in my heart the webhost of the new core object of ASP (a) Http://dwz.cn/6QEdxY minimalist version ASP. Core Learning Path Http://dwz.cn/6QEehK
ASP. NET core integrates with existing system certifications