zoukankan      html  css  js  c++  java
  • 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未授权

  • 相关阅读:
    遍历卷,遍历磁盘
    宽字符
    GetSystemDirectory
    WIN32_FILE_ATTRIBUTE_DATA structure
    几条shell命令
    log4j学习(二)不同类的日志输出到不同的文件
    Java中的split和join
    如何使用socket进行java网络编程(二)
    如何使用socket进行java网络编程(一)
    log4j学习(一)最简单的例子
  • 原文地址:https://www.cnblogs.com/qinzb/p/9363210.html
Copyright © 2011-2022 走看看