淘先锋技术网

首页 1 2 3 4 5 6 7

1.JWTConfig模型类

  /// <summary>
    /// Authentication生成的信息
    /// </summary>
    public class JWTConfig
    {
        /// <summary>
        /// 发布者
        /// </summary>
        public string Issure { get; set; }
        /// <summary>
        /// 接受者
        /// </summary>
        public string Audience { get; set; }
        /// <summary>
        /// 签名秘钥
        /// </summary>
        public string SecurityKey { get; set; }
        /// <summary>
        /// 过期时间(分钟)
        /// </summary>
        public int TokenExpiresMinutes { get; set; }
    }

2.HSJWTService接口类和实现类

 public interface IHSJWTService
    {
        string CreateToken(string createId);
    }

    public class HSJWTService:IHSJWTService
    {
        private readonly JWTConfig JWTConfig;
        public HSJWTService(IOptionsMonitor<JWTConfig> JWTConfigOptions)
        {
            this.JWTConfig = JWTConfigOptions.CurrentValue;
        }

        #region CreateToken
        /// <summary>
        /// 获取Token
        /// </summary>
        public string CreateToken(string createId)
        {
            var claims = new[] {
                new Claim(ClaimTypes.Name,createId),
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.JWTConfig.SecurityKey)); // 获取SecurityKey
            var expires = DateTime.Now.Add(TimeSpan.FromMinutes(this.JWTConfig.TokenExpiresMinutes));
            var token = new JwtSecurityToken(
                   issuer: this.JWTConfig.Issure,   // 发布者
                   audience: this.JWTConfig.Audience, // 接收者
                   notBefore: DateTime.Now,   // token签发时间
                   expires: expires, // token过期时间
                   claims: claims, // 该token内存储的自定义字段信息
                   signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)    // 用于签发token的秘钥算法
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        } 
        #endregion
    }

3.在appsettings.json文件中添加以下信息

  "Authentication": {
    "Issure": "LYGame", //Token发布者
    "Audience": "EveryOneClient", //Token接受者
    "SecurityKey": "LYGAME&LY202111070DANIEL", //签名秘钥长度最少16
    "TokenExpiresMinutes": 1440 //过期时间(分钟)
  }

4.在Startup类ConfigureServices方法中读取配置文件jwt信息,并设置JWT验证

      var sectionAuth = Configuration.GetSection("Authentication");
            // 读取配置文件配置的jwt相关配置
            //services.Configure<JWTConfig>(sectionAuth);
      services.AddAuthentication(options =>
            {   //启用JWT验证
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateAudience = true, //验证接收者
                    ValidateIssuer = true, //验证发布者
                    ValidateLifetime = true, //验证过期时间
                    ValidateIssuerSigningKey = true,//验证秘钥
                    ValidIssuer = sectionAuth["Issure"], //读取Issure
                    ValidAudience = sectionAuth["Audience"], //读配置Audience
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(sectionAuth["SecurityKey"])),  //设置生成Token的秘钥
                    ClockSkew = TimeSpan.Zero  // 默认允许 300s 的时间偏移量,设置为0即可
                };
                options.Events = new JwtBearerEvents
                {
                    OnChallenge = context =>
                    {
                        //终止默认的返回结果(必须有)
                        context.HandleResponse();
                        var result = JsonConvert.SerializeObject(new { status = "401", message = "登录已过期" });
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        context.Response.WriteAsync(result);
                        return Task.FromResult(0);
                    }
                };
            });
          // 添加跨域
            services.AddCors(options => options.AddPolicy("CorsPolicy",
                 builder =>
                 {
                     builder.AllowAnyMethod()
                         .SetIsOriginAllowed(_ => true)
                         .AllowAnyHeader()
                         .AllowCredentials();
                 }));