One, the NuGet used:
1. SYSTEM.IDENTITYMODEL.TOKENS.JWT
2. Microsoft.AspNetCore.Authentication.JwtBearer
Second, in the Startup.cs configuration to add the following services
usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingSystem.Text;usingMicrosoft.IdentityModel.Tokens;usingMicrosoft.AspNetCore.Authentication.JwtBearer;namespacewebapplication1{ Public classStartup { PublicStartup (iconfiguration configuration) {Configuration=configuration; } PublicIConfiguration Configuration {Get; } //This method gets called by the runtime. Use this method to add services to the container. Public voidconfigureservices (iservicecollection services) {services. Addmvc (); //Manual HighlightingServices. Addauthentication (Jwtbearerdefaults.authenticationscheme). Addjwtbearer (Options={options. Tokenvalidationparameters=Newtokenvalidationparameters {Validateissuer=true,//whether to verify issuerValidateaudience =true,//whether to verify audienceValidatelifetime =true,//whether to verify the expiration timeValidateissuersigningkey =true,//whether to verify SecurityKeyValidaudience ="haos.test.com", //The two issuer,audience at the same time as the issuing token.Validissuer ="haos.test.issuer.com", Issuersigningkey=NewSymmetricsecuritykey (Encoding.UTF8.GetBytes ("1234567887654321"))//get the token encryption key. Must be 16 characters }; }); } //This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) { // manually highlight the app. Useauthentication (); if(env. Isdevelopment ()) {app. Usedeveloperexceptionpage (); App. Usebrowserlink (); } Else{app. Useexceptionhandler ("/error"); } app. Usestaticfiles (); App. USEMVC (Routes={routes. MapRoute (Name:"default", Template:"{controller}/{action=index}/{id?}"); }); } }}
Third, issue token add test controller
using microsoft.aspnetcore.authorization;using microsoft.aspnetcore.mvc;using Microsoft.IdentityModel.Tokens; Using system;using system.identitymodel.tokens.jwt;using system.security.claims;using System.Text;using System.Linq ; namespace webapplication1.controllers{[authorize] public class Testcontroller:controller {public jsonre Sult Test () {//get current User information varClaims =User.claims; varUserName =User.Identity.Name; varUserId = claims. FirstOrDefault (t = T.type = = "UserId"); varPhone = claims. FirstOrDefault (t = T.type = =Claimtypes.mobilephone); returnJson ("OK"); } ///<summary> ///Login (token issued) ///</summary> ///<param name= "name" ></param> ///<param name= "pwd" ></param> ///<returns></returns>[allowanonymous] public jsonresult Login (string name, string pwd) {varClaims =New[] { NewClaim (claimtypes.name, "test"), NewClaim (Claimtypes.mobilephone, "157****7350"), NewClaim ("UserId", "value")) }; varKey =NewSymmetricsecuritykey (Encoding.UTF8.GetBytes ("1234567887654321")); varCreds =Newsigningcredentials (key, securityalgorithms.hmacsha256); vartoken =NewJwtsecuritytoken (issuer:"Haos.test.issuer.com", Audience:"Haos.test.com", Claims:claims, Expires:DateTime.Now.AddMinutes (30), signingcredentials:creds); returnJson (New{Authorization= $ "Bearer {new Jwtsecuritytokenhandler (). Writetoken (token)} " }); } }}
// token returned; Note: The key is authorization, which must have the bearer typeface {"Authorization": "Bearer Eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjodhrwoi8vc2nozw1hcy54bwxzb2fwlm9yzy93cy8ymda1lza1l2lkzw50axr5l2nsywltcy9uyw1lijoi Dgvzdcisimh0dha6ly9zy2hlbwfzlnhtbhnvyxaub3jnl3dzlziwmduvmduvawrlbnrpdhkvy2xhaw1zl21vymlszxbob25lijoimtu3kioqkjczntailcjle Haioje1mtc0njgzndcsimlzcyi6imhhb3mudgvzdc5pc3n1zxiuy29tiiwiyxvkijoiagfvcy50zxn0lmnvbsj9.xtrbbz6wf4vreob-s2nmrl5lx1vg27wcq Ytsek5vpic "}
Iv. results of the visit
. Net Core API Licensing Certification