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未授权

 

posted @ 2018-07-24 22:56  深圳丶追  阅读(194)  评论(0编辑  收藏  举报