ASP. NET Core 2.0 uses JWT for authorization authentication

Source: Internet
Author: User
Tags webp

Background

Under the micro-service architecture, the whole system is divided into separate subsystems according to different business or functions, and then communicated through the rest API or RPC and called each other to form a series structure between subsystems. Here, we will use the rest API's communication method. Like what:

1. There is a "User Center" standalone subsystem named "Lezhima.userhub", which is a project based on ASP. NET Core MVC 2.0.

2. There is a standalone subsystem called "Lezhima.userorder" that processes user orders and is a project based on the ASP. NET Core WEBP API 2.0.

3. There is also a standalone subsystem called "Lezhima.userupload" that handles user file uploads, and is a project based on the ASP. NET Core WEBP API 2.0.

The business relationship is as follows:

After the user successfully login to "Lezhima.userhub", when the user view the order through the front-end Ajax call "Lezhima.userorder" Web API interface, the user uploads the picture is through the front-end Ajax calls " Lezhima.userupload "Web API interface.

At this point, we understand the above business relationship, the heart must produce the following two questions:

1, how to protect the "Lezhima.userorder" and "lezhima.userupload" two separate systems within the Web API interface security, because they have been exposed to the front-end.

2, how to issue tokens at "Lezhima.userhub" station.

So, with the problem we're going to discuss specific implementations with the JWT technology that comes with ASP. (Maybe smart you have a better solution, please tell me, thank you).

The JWT full name is: JSON Web Token, is a very mature technology, the garden also has a lot of this knowledge, I will not repeat here.

Implementation principle

"Lezhima.userhub" station because we have already done login verification, we think it is credible, so in front of the AJAX request "Lezhima.userorder" station Web API interface first to the back end to generate a token, And with this cross-site request to carry to the "Lezhima.userorder" station, "Lezhima.userorder" station to verify the token in the request header is legitimate, such as legitimate continue to route to the specific method, otherwise end the request. The "Lezhima.userupload" station principle is the same as "Lezhima.userorder".

Implementation code

Lezhima.userhub Issue Token code:

        <summary>////issue a token with a specified validity period and pass in the user ID of the current login///</summary>//<param NA Me= "Currentuserid" ></param>//<param name= "expiresminutes" ></param>//&LT;RETURNS&G        t;</returns> public static Async task<string> Getaccesstoken (string currentuserid,int expiresminutes=2) {return await task.run () = {//Contract private key, the following three parameters can be placed in the configuration file var secret = "Nguznmnlnzqtz                THKZC00YJRH ";//issuer var ISS =" Andre ";//recipient var AUD =" Andre "; if (string. IsNullOrEmpty (Secret) | | String. IsNullOrEmpty (ISS) | | String.                IsNullOrEmpty (AUD)) return ""; if (string. IsNullOrEmpty (currentuserid)) Currentuserid = Guid.NewGuid ().                ToString ();                var now = Datetime.utcnow; var claims = new claim[] {new Claim (jwtregisteredclaimnames.sub, CurrentuSerid), New Claim (Jwtregisteredclaimnames.iat, now. ToUniversalTime ().                ToString (), claimvaluetypes.integer64)};                var signingkey = new Symmetricsecuritykey (Encoding.ASCII.GetBytes (secret));                       var JWT = new Jwtsecuritytoken (Issuer:iss, Audience:aud, Claims:claims, Notbefore:now, Expires:now. ADD (Timespan.fromminutes (expiresminutes)), Signingcredentials:new signingcredentials (Signingkey, Se                curityalgorithms.hmacsha256)); return new Jwtsecuritytokenhandler ().            Writetoken (JWT);                   }); }

Lezhima.userhub front-end Ajax cross-site request code:

Encapsulates an AJAX request public method function Getwebdatabyobject (URL, Requestmethon, paramter) {    jQuery.support.cors = true;    Apiurl = ' http://127.0.0.1:8012/';    var token = GetToken (); Call the token in this site to issue the Web API interface     var result = [];    $.ajax ({        Type:requestmethon,        url:apiurl + URL,        data:paramter,        async:false,        beforesend: function (XHR) {//Carry token to the request header            Xhr.setrequestheader ("Authorization", "Bearer" + token);        },          success: function (data) {            result = data;        },        error:function (XMLHttpRequest, Textstatus, Errorthrown) {            // Status Code            console.log (xmlhttprequest.status);            State            Console.log (xmlhttprequest.readystate);            Error message               Console.log (textstatus);        }    });    return result;}

"Lezhima.userorder" station to open the token verification of JWT, add the following code in the Startup.cs:

        Public IServiceProvider configureservices (iservicecollection services) {services. Addcors ();//Obtain the private key from the configuration file, Publisher, recipient three parameters//three parameter values must be the same as the issuing token station var audienceconfig = configuration.getsection ("Audience            ");            var signingkey = new Symmetricsecuritykey (Encoding.ASCII.GetBytes (audienceconfig["Secret"]));                 var tokenvalidationparameters = new Tokenvalidationparameters {Validateissuersigningkey = True, Issuersigningkey = Signingkey, Validateissuer = true, Validissuer = Audience                config["Iss"], Validateaudience = true, Validaudience = audienceconfig["Aud"],            Validatelifetime = true, Clockskew = TimeSpan.Zero, Requireexpirationtime = True, };//injects JWT validation services. Addauthentication (Jwtbearerdefaults.authenticationscheme).             Addjwtbearer (options =       Options.                    Requirehttpsmetadata = false; Options.                Tokenvalidationparameters = tokenvalidationparameters;            }); Services.            Addmvc ();            var builder = new Containerbuilder (); Builder.            Registermodule (New Evolution ()); Builder.            Populate (services); var container = Builder.            Build (); Return container.        Resolve<iserviceprovider> (); }
        public void Configure (Iapplicationbuilder app, ihostingenvironment env)        {            if (env. Isdevelopment ())            {                app. Usedeveloperexceptionpage ();            }            App. Usecors (builder =              builder). Withorigins ("*")              . Allowanyheader ()              . Allowanymethod ()              . Allowcredentials ()            );                     Turn on the verification            app. Useauthentication ();            App. Usemvc ();        }

Add a validation filter [authorize] to the controller inside the "Lezhima.userorder" station, as shown in the following code:

    [Route ("Api/[controller]")]    After adding a filter, all actions within the controller will be token verified    [authorize] public    class Ordercontroller:controller    {            }

  

At this point, the JWT cross-site verification token scheme based on the ASP. NET core is all done, isn't it simple ^_^ ^_^

ASP. NET Core 2.0 uses JWT for authorization 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.