| | 1 | | using System.Text; |
| | 2 | | using Microsoft.IdentityModel.Tokens; |
| | 3 | | using System.IdentityModel.Tokens.Jwt; |
| | 4 | |
|
| | 5 | | namespace Syki.Back.Configs; |
| | 6 | |
|
| | 7 | | public static class AuthenticationConfigs |
| | 8 | | { |
| | 9 | | public const string BearerScheme = "Bearer"; |
| | 10 | |
|
| | 11 | | public static void AddAuthenticationConfigs(this IServiceCollection services) |
| | 12 | | { |
| 1 | 13 | | using var serviceProvider = services.BuildServiceProvider(); |
| 1 | 14 | | var settings = serviceProvider.GetService<AuthSettings>()!; |
| | 15 | |
|
| 1 | 16 | | JwtSecurityTokenHandler.DefaultMapInboundClaims = false; |
| 1 | 17 | | JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); |
| | 18 | |
|
| 1 | 19 | | var tokenValidationParameters = new TokenValidationParameters |
| 1 | 20 | | { |
| 1 | 21 | | ValidateIssuer = true, |
| 1 | 22 | | ValidIssuer = settings.Issuer, |
| 1 | 23 | |
|
| 1 | 24 | | ValidateIssuerSigningKey = true, |
| 1 | 25 | | IssuerSigningKey = new SymmetricSecurityKey( |
| 1 | 26 | | Encoding.ASCII.GetBytes(settings.SecurityKey) |
| 1 | 27 | | ), |
| 1 | 28 | |
|
| 1 | 29 | | ValidAlgorithms = [ "HS256" ], |
| 1 | 30 | |
|
| 1 | 31 | | ValidateAudience = true, |
| 1 | 32 | | ValidAudience = settings.Audience, |
| 1 | 33 | |
|
| 1 | 34 | | ValidateLifetime = true, |
| 1 | 35 | | ClockSkew = TimeSpan.Zero, |
| 1 | 36 | |
|
| 1 | 37 | | RoleClaimType = "role", |
| 1 | 38 | | }; |
| | 39 | |
|
| 1 | 40 | | services.AddAuthentication(BearerScheme) |
| 1 | 41 | | .AddJwtBearer(BearerScheme, options => |
| 1 | 42 | | { |
| 1 | 43 | | options.TokenValidationParameters = tokenValidationParameters; |
| 2 | 44 | | }); |
| 2 | 45 | | } |
| | 46 | | } |