Пример #1
0
 public static void AddJwt(this IServiceCollection services, JwtConfig config)
 {
     //添加认证配置
     services.AddAuthentication(o =>
     {
         o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
         o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
     })
     .AddJwtBearer(o =>
     {
         //验证配置,比如是否验证发布者,订阅者,密钥,以及过期时间等
         o.TokenValidationParameters = new TokenValidationParameters
         {
             ValidateIssuer           = true,
             ValidIssuer              = config.Issuer,
             ValidateIssuerSigningKey = true,
             IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.SecurityKey)),
             ValidateAudience         = true,
             ValidAudience            = config.Audience,
             ValidateLifetime         = true,
             RequireExpirationTime    = true,
             //ClockSkew = TimeSpan.FromMinutes(config.ClockSkew)//总的Token有效时间 = JwtRegisteredClaimNames.Exp + ClockSkew
         };
     });
 }
Пример #2
0
        /// <summary>
        /// 生成基于JWT的Token
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static JwtToken BuildJwtToken(Claim[] claims, JwtConfig config)
        {
            var now = DateTime.Now;

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.SecurityKey));
            //实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                issuer: config.Issuer,
                audience: config.Audience,
                claims: claims,
                notBefore: now,
                expires: now.AddMinutes(config.Expiration),
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
                );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new JwtToken
            {
                AccessToken = encodedJwt,
                Expiration = now.AddMinutes(config.Expiration),
            });
        }