-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJwtConfig.cs
72 lines (68 loc) · 2.79 KB
/
JwtConfig.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using Application.Interface.Setting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Infrastructure.JwtService
{
public static class JwtConfig
{
public static IServiceCollection AddAuthenticationJwt(this IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();
string issuer = string.Empty;
string audience = string.Empty;
string secretkey = string.Empty;
using (var scope = serviceProvider.CreateScope())
{
var appSettingService = scope.ServiceProvider.GetService<IAppSettingService>();
issuer = appSettingService.GetValue("Jwt.Issuer");
audience = appSettingService.GetValue("Jwt.Audience");
secretkey = appSettingService.GetValue("Jwt.SecretKey");
}
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = issuer,
ValidAudience = audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretkey)),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
};
options.SaveToken = true; // HttpContext.GetTokenAsunc();
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
//log
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
//log
return Task.CompletedTask;
},
OnChallenge = context =>
{
return Task.CompletedTask;
},
OnMessageReceived = context =>
{
return Task.CompletedTask;
},
OnForbidden = context =>
{
return Task.CompletedTask;
}
};
});
return services;
}
}
}