public static IServiceCollection AddJwtSetup(this IServiceCollection services, string key)
        {
            // string issue = ConfigurationManager.Appsetting("JWT", "Issue"); // "Issuer";
            //string aud = ConfigurationManager.Appsetting("JWT", "Aud"); // "Audience";
            // string secret = ConfigurationManager.Appsetting("JWT", "Secret"); // "ghgfopkhop gkfdopg kdfpgkdfg dfgkdfg dfgf gfdg";

            //var jwtConfig = ConfigurationManager.GetSection<JwtTokenSetting>("JWT");

            //if (jwtConfig != null)
            //{
            //    throw new Exception("请配置JWT节点");
            //}

            var jwtConfig = JwtTokenSetting.GetKey(key);

            services.AddAuthentication(x =>
            {
                //看这个单词熟悉么?没错,就是上边错误里的那个。
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })// 也可以直接写字符串,AddAuthentication("Bearer")
            .AddJwtBearer(o =>
            {
                var keyByteArray = System.Text.Encoding.ASCII.GetBytes(jwtConfig.Secret);
                var signingKey   = new SymmetricSecurityKey(keyByteArray);

                //var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,    //是否验证Issuer
                    ValidateAudience         = true,    //是否验证Audience
                    ValidateIssuerSigningKey = true,    //是否验证IssuerSigningKey
                    ValidateLifetime         = true,    //是否验证超时  当设置exp和nbf时有效 同时启用ClockSkew

                    ValidIssuer      = jwtConfig.Issue, //发行人
                    ValidAudience    = jwtConfig.Aud,   //订阅人
                    IssuerSigningKey = signingKey,      //参数配置在下边


                    //ClockSkew = TimeSpan.Zero,//这个是缓冲过期时间,也就是说,即使我们配置了过期时间,这里也要考虑进去,过期时间+缓冲,默认好像是7分钟,你可以直接设置为0
                    ClockSkew = jwtConfig.GetClickSkew(),

                    RequireExpirationTime = true,
                };
            });

            return(services);
        }
Example #2
0
        public static string IssueJwt(TokenModelOptions options)
        {
            //string issue = ConfigurationManager.Appsetting("JWT", "Issue"); // "Issuer";
            //string aud = ConfigurationManager.Appsetting("JWT", "Aud"); // "Audience";
            //string secret = ConfigurationManager.Appsetting("JWT", "Secret"); // "ghgfopkhop gkfdopg kdfpgkdfg dfgkdfg dfgf gfdg";

            //var jwtConfig = ConfigurationManager.Appsetting("JWT");

            var jwtConfig = JwtTokenSetting.GetKey(options.AppId);


            //var jwt1 = ;

            //var claims = new List<Claim>
            //{
            //    new Claim("jti", tokenModel.Uid.ToString()),
            //    new Claim("iat", $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
            //    new Claim("nbf",$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
            //    //这个就是过期时间,目前是过期1000秒,可自定义,注意JWT有自己的缓冲过期时间
            //    new Claim ("exp",$"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
            //    new Claim("iss",issue ),
            //    new Claim("aud",aud),
            //};

            var expires = jwtConfig.GetExpires();

            var claims = new List <Claim>
            {
                //下边为Claim的默认配置
                new Claim(JwtRegisteredClaimNames.Jti, options.Id),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                //这个就是过期时间,目前是过期100秒,可自定义,注意JWT有自己的缓冲过期时间
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.Add(expires)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss, jwtConfig.Issue),
                new Claim(JwtRegisteredClaimNames.Aud, jwtConfig.Aud),
                //这个Role是官方UseAuthentication要要验证的Role,我们就不用手动设置Role这个属性了
                //new Claim(ClaimTypes.Role,tokenModel.Role),
                //new Claim(ClaimTypes.Name, tokenModel.Name),
                //new Claim(ClaimTypes.NameIdentifier, tokenModel.Id.ToString()),
            };


            //claims.AddRange(tokenModel.Role.Select(s => new Claim(ClaimTypes.Role, s.Trim())));

            //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken
                      (
                issuer: jwtConfig.Issue,
                claims: claims,
                signingCredentials: creds

                      );

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

            return(encodedJwt);
        }