一、所使用到的NuGet:
1. System.IdentityModel.Tokens.Jwt
2. Microsoft.AspNetCore.Authentication.JwtBearer
二、在Startup.cs 中配置添加如下处事
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.Text; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Authentication.JwtBearer; namespace WebApplication1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //手动高亮 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证掉效时间 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidAudience = "haos.test.com", //山下这两项和签发token时的issuer,Audience一致 ValidIssuer = "haos.test.issuer.com", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321"))//拿到token加密密钥.必需是16个字符 }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //手动高亮 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?}"); }); } } }
三、签发token 添加测试控制器
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 JsonResult Test() { //获取当前用户信息 var claims = User.Claims; var userName = User.Identity.Name; var userId = claims.FirstOrDefault(t => t.Type == "userId"); var phone = claims.FirstOrDefault(t => t.Type == ClaimTypes.MobilePhone); return Json("ok"); } /// <summary> /// 登录(签发token) /// </summary> /// <param></param> /// <param></param> /// <returns></returns> [AllowAnonymous] public JsonResult Login(string name ,string pwd) { var claims = new[] { new Claim(ClaimTypes.Name, "test"), new Claim(ClaimTypes.MobilePhone, "157****7350"), new Claim("userId","value") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "haos.test.issuer.com", audience: "haos.test.com", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return Json(new { Authorization = $"Bearer {new JwtSecurityTokenHandler().WriteToken(token)}" }); } } }