38-JWT 设计解析及定制
Posted qinzb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了38-JWT 设计解析及定制相关的知识,希望对你有一定的参考价值。
可去官网下载Security项目查看源码
只需修改 AddJwtBearer中的行为即可
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings")); var jwtSetting = new JwtSettings(); Configuration.Bind("JwtSettings",jwtSetting); services.AddAuthentication(options=>{ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(jwtOption=>{ // jwtOption.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{ // ValidIssuer = jwtSetting.Issure, // ValidAudience = jwtSetting.Audience, // IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey( // System.Text.Encoding.UTF8.GetBytes(jwtSetting.SecretKey) // ) // }; jwtOption.SecurityTokenValidators.Clear(); jwtOption.SecurityTokenValidators.Add(new MyTokenValidator()); jwtOption.Events = new JwtBearerEvents(){ OnMessageReceived = Context=>{ var token = Context.Request.Headers["token"]; Context.Token = token; return Task.CompletedTask; } }; }); }
自定义验证类的实现,需实现ISecurityTokenValidator接口
using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Authentication.JwtBearer; namespace JwtAuthSample.Auth { public class MyTokenValidator : ISecurityTokenValidator { bool ISecurityTokenValidator.CanValidateToken => true; public int MaximumTokenSizeInBytes { get;set; } public bool CanReadToken(string securityToken) { return true; } public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { validatedToken = null; if(securityToken!="abcdefg"){ return new ClaimsPrincipal();; } var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme); identity.AddClaim(new Claim("name","qinzb")); identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType,"admin")); var prinipal = new ClaimsPrincipal(identity); return prinipal; } } }
访问方式,如果token不对,则会返回401未授权
以上是关于38-JWT 设计解析及定制的主要内容,如果未能解决你的问题,请参考以下文章
Django运维后台的搭建之三:用url去精细定制与反向解析
Python 地图篇 - 使用pyecharts最新版本绘制中国地图实例详解,个性化地图定制及常用参数解析
Springboot2之静态资源规则与定制化welcome与favicon功能Rest映射及源码解析以及改变默认的_method
Springboot2之静态资源规则与定制化welcome与favicon功能Rest映射及源码解析以及改变默认的_method