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

1、框架增加Identity注册功能

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

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

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

 

JWTtoken生成代码:

 private string CreateAccessToken(IEnumerable<Claim> 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<YMNUser, Role>()
  .AddEntityFrameworkStores<YMNContext>() ;
            //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;
                //    }
                //};
            });

 

posted on 2020-02-06 12:56  topguntopgun  阅读(499)  评论(0编辑  收藏  举报

导航