你的位置:首页 > ASP.net教程

[ASP.net教程].net core Jwt 添加


    Jwt 已经成为跨平台身份验证通用方案,如不了解请关注:https://jwt.io/。   

    为了和微软其他验证模块有个比较好的衔接,项目中采用了微软开发的jwt组件: System.IdentityModel.Tokens.Jwt。首先安装:Install-Package System.IdentityModel.Tokens.Jwt。

   在config方法中添加

    

1 if (!HostingEnvironment.IsEnvironment("test"))2       {3         app.UseJwtBearerAuthentication(Jwt.GetJwtOptions());4       }

 实现一个jwt工具类:

 1 using System; 2 using System.Collections.Generic; 3 using System.IdentityModel.Tokens.Jwt; 4 using System.Security.Claims; 5 using System.Text; 6 using System.Threading.Tasks; 7 using AutoMapper; 8 using Microsoft.AspNet.Hosting; 9 using Microsoft.AspNetCore.Authentication.JwtBearer;10 using Microsoft.AspNetCore.Builder;11 using Microsoft.AspNetCore.Hosting;12 using Microsoft.AspNetCore.Http;13 using Microsoft.AspNetCore.Http.Extensions;14 using Microsoft.Extensions.Configuration;15 using Microsoft.IdentityModel.Tokens;16 using NDaisy.Core.ServiceLocator;17 using WebApiCore.Core.Utility.Extension;18 using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;19 20 namespace WebApiCore.Utility21 {22   public class Jwt23   {24     private static SecurityKey _signKey;25     private static IConfigurationSection _config;26     private const string Issue = "webcore";27     static Jwt()28     {29       _config= ServiceLocator.Current.GetInstance<IConfigurationRoot>().GetSection("Jwt");30       var keyAsBytes = Encoding.ASCII.GetBytes(_config.GetValue<string>("Salt"));31       _signKey = new SymmetricSecurityKey(keyAsBytes);32        33     }34 35     public static JwtBearerOptions GetJwtOptions()36     {37       return new JwtBearerOptions38       {39         TokenValidationParameters =40         {41           ValidIssuer = Issue,42           IssuerSigningKey = _signKey,43           ValidateLifetime = true,44           ValidateIssuer = true,45           ValidateAudience = false46         },47          Events = new JwtBearerEvents()48          {49            OnAuthenticationFailed = c =>50            {51              52              return Task.Run(() =>53              {54                if (ServiceLocator.Current.GetInstance<IHostingEnvironment>().IsDevelopment())55                {56                  c.Request.GetDisplayUrl().LogInfo();57                  c.Exception.LogError();58                }59 60              } );61            }62          63          }64       };65     }66 67     public static string SignToken(IList<Claim> claims)68     {69       var seconds= _config.GetValue<int>("SlideTime");70       71       JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: Issue, claims: claims, expires: DateTime.UtcNow.AddSeconds(seconds), signingCredentials: new SigningCredentials(_signKey, SecurityAlgorithms.HmacSha256));72       73       return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);74     }75   }76 77 }

View Code

添加一个获取token的入口,实际项目中,放在登录授权里面:

1 app.Map("/auth/test", appbuilder =>2       {3         appbuilder.Run(d =>4         {5           var token= Jwt.SignToken(new List<Claim>() {new Claim("name", "ryan")});6          7           return d.Response.WriteAsync(token);8         });9       });