1. 程式人生 > >38-JWT 設計解析及定制

38-JWT 設計解析及定制

bcd quest lai void all security mod size asp

可去官網下載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 設計解析及定制