zoukankan      html  css  js  c++  java
  • 开源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;
                    //    }
                    //};
                });
  • 相关阅读:
    ElasticSearch 分词器
    ElasticSearch 搜索引擎概念简介
    Kibana,Logstash 和 Cerebro 的安装运行
    ElasticSearch 安装与运行
    ElasticSearch 入门简介
    SVM 支持向量机算法-实战篇
    SVM 支持向量机算法-原理篇
    nginx 访问限速
    nginx 开启 autoindex
    nginx 开启 gzip 压缩
  • 原文地址:https://www.cnblogs.com/topguntopgun/p/12268314.html
Copyright © 2011-2022 走看看