JWT ASP. NET MVC Authentication

Source: Internet
Author: User
Tags httpcontext

Json Web Token (JWT)

A good authentication and authorization scheme, in contrast to the Session, JWT stores the user information in the Token's payload field on the client side, ensuring that the data will not be tampered with, and verifying the validity of the data, by means of RSA encryption.

Please refer to Jwt.io for details. I am still a small white, hoping to help more small white growth. Therefore the article is some relatively simple use process, the text explanation is less, afraid fraught.

Small white grow into the process of the Daniel: know it but do not know the lead

And then know that it is not yet known

1. The development environment is as follows

Vs2017+asp.net MVC 5+.net FrameWork4.5.2

2. Add a framework that encapsulates the JWT used first on NuGet

Because the environment is . NET FrameWork4.5.2 So I'm using the 3.0.1 version

3. Encapsulation of a JWT helper class

Create an entity class UserInfo

public string UserName {get; set;}

public string Pwd {get; set;}

     Public classJwthelp {//configuration in private key Web. config//"GQDSTCKSX0NHJPOUXOYG5MBEJ1XT0UFIWDVVVBRK";        Private Static stringSecret = configurationmanager.appsettings["Secret"].        ToString (); /// <summary>        ///Generate Jwttoken/// </summary>        /// <param name= "payload" >non-sensitive user data</param>        /// <returns></returns>         Public Static stringSetjwtencode (dictionary<string,Object>payload) {            //The format is as follows//var payload = new dictionary<string, object>//{            //{"username", "admin"},//{"pwd", "Claim2-value"}//};Ijwtalgorithm Algorithm=NewHmacsha256algorithm (); Ijsonserializer Serializer=NewJsonnetserializer (); Ibase64urlencoder Urlencoder=NewJwtbase64urlencoder (); Ijwtencoder Encoder=NewJwtencoder (algorithm, serializer, urlencoder); vartoken =Encoder.            Encode (payload, secret); returntoken; }        /// <summary>        ///get entities based on Jwttoken/// </summary>        /// <param name= "token" >Jwttoken</param>        /// <returns></returns>         Public StaticUserInfo Getjwtdecode (stringtoken) {Ijsonserializer Serializer=NewJsonnetserializer (); Idatetimeprovider provider=NewUtcdatetimeprovider (); Ijwtvalidator Validator=NewJwtvalidator (serializer, provider); Ibase64urlencoder Urlencoder=NewJwtbase64urlencoder (); Ijwtdecoder Decoder=NewJwtdecoder (Serializer, validator, urlencoder); varUserInfo = decoder. Decodetoobject<userinfo> (token, secret, verify:true);//token for the previously generated string            returnUserInfo; }    }}

4. Create a Jwtcontroller build Jwttoken see the effect

The Get request needs to be changed to this

Return Json (Result,jsonrequestbehavior.allowget);

 Public classJwtcontroller:controller {//GET:JWT         PublicActionResult Index () {returnView (); }        /// <summary>        ///Create Jwttoken/// </summary>        /// <param name= "username" ></param>        /// <param name= "pwd" ></param>        /// <returns></returns>         PublicActionResult Createtoken (stringUsernamestringpwd) {Dataresult result=NewDataresult (); //Suppose the username is "admin" and the password is "123"            if(Username = ="Admin"&& pwd = ="123")            {                varPayload =Newdictionary<string,Object>                {                    { "username", username}, {"pwd", pwd}}; Result. Token=Jwthelp.setjwtencode (payload); Result. Success=true; Result. Message="Success"; }            Else{result. Token=""; Result. Success=false; Result. Message="token generation failed"; }            returnJson (result);
Get requests need to be modified to this
Return Json (Result,jsonrequestbehavior.allowget); } }

5. I like postman test artifact you deserve to have

6.Authorizeattribute

Next, we need to write code about permission control and token parsing.

All actions are tagged with the restricted action or controller in the home, and all access is subject to authorization before access

Write an inherited Authorizeattribute implementation class, based on whether the entity classes are equal.

Let me briefly describe the program execution process.

1. Go to Verification Portal, verify core code,

1. Return false into validation processing failed

2. Return true to access the controller/action inside

 Public classMyauthorizeattribute:authorizeattribute {/// <summary>        ///Validate Entry/// </summary>        /// <param name= "Filtercontext" ></param>         Public Override voidonauthorization (AuthorizationContext filtercontext) {Base.        Onauthorization (Filtercontext); }        /// <summary>        ///Verifying the core code/// </summary>        /// <param name= "HttpContext" ></param>        /// <returns></returns>        protected Override BOOLAuthorizecore (HttpContextBase HttpContext) {//The front-end request API will store tokens in the request header named "Auth"            varAuthheader = httpcontext.request.headers["Auth"]; if(Authheader = =NULL) {HttpContext.Response.StatusCode=403; return false; }            varUserInfo =Jwthelp.getjwtdecode (Authheader); //For example, generate a jwttoken into Redis//this place uses Jwttoken as key to get the entity Val and see if Jwttoken is the same as Redis .            if(UserInfo. UserName = ="Admin"&& UserInfo. PWD = ="123")                return true; HttpContext.Response.StatusCode=403; return false; }        /// <summary>        ///Validation Failure handling/// </summary>        /// <param name= "Filtercontext" ></param>        protected Override voidhandleunauthorizedrequest (AuthorizationContext filtercontext) {Base.            Handleunauthorizedrequest (Filtercontext); if(FilterContext.HttpContext.Response.StatusCode = =403) {Filtercontext.result=NewRedirectresult ("/error"); FilterContext.HttpContext.Response.Redirect ("/home/error"); }        }    }

Use postman and then headers place jswtoken into it.

Reference links

Https://www.cnblogs.com/lwhkdash/p/6686999.html

Https://www.cnblogs.com/cnki/p/6297182.html

GitHub download Link the above error, please forgive us. I'm still a little white.

Https://github.com/yaols/JWT.MvcDemo

JWT ASP. NET MVC Authentication

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.