开源DDD设计模式框架YMNNetCoreFrameWork第二篇-增加ASp.net core Identity身份认证,JWT身份认证

2021-04-19 13:27

阅读:506

标签:except   eval   scheme   nbsp   service   user   cep   create   ring   

1、框架增加Identity注册功能

2、框架增加identity登录以后获取JWTtoken

3、请求接口通过token请求,增加验证特性

源代码地址:https://github.com/topgunymn/YMNNetCoreFrameWork

 

JWTtoken生成代码:

 private string CreateAccessToken(IEnumerable claims, TimeSpan? expiration = null)
        {
            var now = DateTime.UtcNow;
            SymmetricSecurityKey symmetricSecurityKey =   new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration.GetSection("Authentication:JwtBearer")["SecurityKey"].ToString()));
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: _configuration.GetSection("Authentication:JwtBearer")["Issuer"].ToString(),
                audience: _configuration.GetSection("Authentication:JwtBearer")["Audience"].ToString(),
                claims: claims,
                notBefore: now,
                expires:now.AddMinutes(30),
                // expires: now.Add(expiration ?? _configuration.Expiration),  SecurityKey
                signingCredentials: new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256)
            );

            return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        }

 

JWT认证配置代码:

services.AddIdentity()
  .AddEntityFrameworkStores() ;
            //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            // //添加jwt验证:
            // .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            // {
            services.AddAuthentication(options =>
            {
                     //identity.application
                     var a = options.DefaultAuthenticateScheme;
                var b = options.DefaultChallengeScheme;
                options.DefaultAuthenticateScheme = "JwtBearer";
                options.DefaultChallengeScheme = "JwtBearer";
            }).AddJwtBearer("JwtBearer", options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime = true,//是否验证失效时间
                    ClockSkew = TimeSpan.FromSeconds(30),

                    ValidateAudience = true,//是否验证Audience
                                            //ValidAudience = Const.GetValidudience(),//Audience
                                            //这里采用动态验证的方式,在重新登陆时,刷新token,旧token就强制失效了
                    AudienceValidator = (m, n, z) =>
                  {
                      return m != null && m.FirstOrDefault().Equals(Audience);
                  },
                    ValidateIssuer = true,//是否验证Issuer
                    ValidIssuer = Issuer,//Issuer,这两项和前面签发jwt的设置一致

                    ValidateIssuerSigningKey = true,//是否验证SecurityKey
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))//拿到SecurityKey
                };
                //options.Events = new JwtBearerEvents
                //{
                //    OnAuthenticationFailed = context =>
                //    {
                //        //Token expired
                //        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                //        {
                //            context.Response.Headers.Add("Token-Expired", "true");
                //        }
                //        return Task.CompletedTask;
                //    }
                //};
            });

 

开源DDD设计模式框架YMNNetCoreFrameWork第二篇-增加ASp.net core Identity身份认证,JWT身份认证

标签:except   eval   scheme   nbsp   service   user   cep   create   ring   

原文地址:https://www.cnblogs.com/topguntopgun/p/12268314.html

上一篇:PHP文件上传

下一篇:PHP简单计算器


评论


亲,登录后才可以留言!