JwtExtensions.cs 2.5 KB
Newer Older
K
kuiyu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * RsCode
 * 
 * RsCode is .net core platform rapid development framework
 * Apache License 2.0
 * 
 * 作者:lrj
 * 
 * 项目己托管于
 * gitee
 * https://gitee.com/rswl/RsCode.git
 * 
 * github
   https://github.com/kuiyu/RsCode.git
 */
using Microsoft.Extensions.DependencyInjection;
K
kuiyu 已提交
17 18 19 20 21 22 23 24 25 26
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.Threading.Tasks;

namespace RsCode.AspNetCore
{
    public  static class JwtExtensions
    {
K
fix err  
kuiyu 已提交
27
        public static  void AddJwt(this IServiceCollection services)
K
kuiyu 已提交
28
        {
K
fix err  
kuiyu 已提交
29 30 31 32 33
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
K
kuiyu 已提交
34 35 36 37 38 39
                .AddJwtBearer(options =>
                {
                    var jwt = JwtHelper.GetJwtInfo();

                    if (jwt.Expire < 0)
                        jwt.Expire = 60*24*360 ;
K
fix err  
kuiyu 已提交
40 41
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
K
kuiyu 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,//是否验证发行者
                        ValidateAudience = true,//是否验证接收者

                        ValidateLifetime = true,//是否验证失效时间
                        ClockSkew = TimeSpan.FromMinutes(jwt.Expire),
                        ValidateIssuerSigningKey = true,//是否验证安全key
                        ValidAudience = jwt.Audience,//有效的接收者
                        ValidIssuer = jwt.Issuer,//有效的发行者 
                        IssuerSigningKey =
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.SecurityKey))
                    };

K
fix err  
kuiyu 已提交
56
                    //auth
K
kuiyu 已提交
57 58 59
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = context =>
K
fix err  
kuiyu 已提交
60 61
                        { 
                            if(context.Request.Query.TryGetValue("access_token", out var accessToken))
K
kuiyu 已提交
62
                            {
K
fix err  
kuiyu 已提交
63 64
								context.Token = accessToken;
							}
K
kuiyu 已提交
65 66 67 68 69 70
                            return Task.CompletedTask;
                        }
                    };
                });

            services.AddScoped<JwtHelper>();
71
      
K
kuiyu 已提交
72 73 74
        }
    }
}