Exemple #1
0
        /// <summary>
        /// 注入jwt
        /// </summary>
        /// <param name="services"></param>
        public static void AddJwtService(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.Configure <JwtConfig>(AppSetting.GetSection("Audience"));

            JwtConfig jwtConfig = new JwtConfig();

            AppSetting.BindSection("Audience", jwtConfig);
            var keyByteArray = Encoding.ASCII.GetBytes(jwtConfig.IssuerSigningKey);
            var signingKey   = new SymmetricSecurityKey(keyByteArray);

            services.AddAuthentication(o =>
            {
                //添加JWT Scheme
                o.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.Name,
                    //是否验证SecurityKey
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = signingKey,
                    ValidateIssuer           = true,
                    ValidIssuer      = jwtConfig.Issuer,   //发行人
                    ValidateAudience = true,
                    ValidAudience    = jwtConfig.Audience, //订阅人
                    // 验证失效时间
                    ValidateLifetime      = true,
                    ClockSkew             = TimeSpan.FromMinutes(jwtConfig.RefreshTokenExpiresMinutes),
                    RequireExpirationTime = true,
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var token    = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                        var jwtToken = (new JwtSecurityTokenHandler()).ReadJwtToken(token);

                        if (jwtToken.Issuer != jwtConfig.Issuer)
                        {
                            context.Response.Headers.Add("Token-Error-Iss", "issuer is wrong!");
                        }

                        if (jwtToken.Audiences.FirstOrDefault() != jwtConfig.Audience)
                        {
                            context.Response.Headers.Add("Token-Error-Aud", "Audience is wrong!");
                        }

                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return(Task.CompletedTask);
                    }
                };
            });
        }