| | 1 | | using System.Text; |
| | 2 | | using Microsoft.IdentityModel.Tokens; |
| | 3 | | using System.IdentityModel.Tokens.Jwt; |
| | 4 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | 5 | |
|
| | 6 | | namespace Syki.Back.Configs; |
| | 7 | |
|
| | 8 | | public static class AuthenticationConfigs |
| | 9 | | { |
| | 10 | | public const string BearerScheme = "Bearer"; |
| | 11 | |
|
| | 12 | | public static void AddAuthenticationConfigs(this WebApplicationBuilder builder) |
| | 13 | | { |
| 2 | 14 | | var settings = builder.Configuration.Auth(); |
| | 15 | |
|
| 2 | 16 | | JwtSecurityTokenHandler.DefaultMapInboundClaims = false; |
| 2 | 17 | | JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); |
| | 18 | |
|
| 2 | 19 | | var tokenValidationParameters = new TokenValidationParameters |
| 2 | 20 | | { |
| 2 | 21 | | ValidateIssuer = true, |
| 2 | 22 | | ValidIssuer = settings.Issuer, |
| 2 | 23 | |
|
| 2 | 24 | | ValidateIssuerSigningKey = true, |
| 2 | 25 | | IssuerSigningKey = new SymmetricSecurityKey( |
| 2 | 26 | | Encoding.ASCII.GetBytes(settings.SecurityKey) |
| 2 | 27 | | ), |
| 2 | 28 | |
|
| 2 | 29 | | ValidAlgorithms = [ "HS256" ], |
| 2 | 30 | |
|
| 2 | 31 | | ValidateAudience = true, |
| 2 | 32 | | ValidAudience = settings.Audience, |
| 2 | 33 | |
|
| 2 | 34 | | ValidateLifetime = true, |
| 2 | 35 | | ClockSkew = TimeSpan.Zero, |
| 2 | 36 | |
|
| 2 | 37 | | RoleClaimType = "role", |
| 2 | 38 | | }; |
| | 39 | |
|
| 2 | 40 | | builder.Services.AddAuthentication(BearerScheme) |
| 2 | 41 | | .AddJwtBearer(BearerScheme, options => |
| 2 | 42 | | { |
| 2 | 43 | | options.TokenValidationParameters = tokenValidationParameters; |
| 2 | 44 | |
|
| 2 | 45 | | options.Events = new JwtBearerEvents |
| 2 | 46 | | { |
| 2 | 47 | | OnMessageReceived = context => |
| 2 | 48 | | { |
| 4990 | 49 | | var cookieJwt = context.Request.Cookies["syki_jwt"]; |
| 4990 | 50 | | if (cookieJwt.HasValue()) |
| 2 | 51 | | { |
| 4988 | 52 | | context.Token = cookieJwt; |
| 4988 | 53 | | return Task.CompletedTask; |
| 2 | 54 | | } |
| 2 | 55 | |
|
| 2 | 56 | | return Task.CompletedTask; |
| 2 | 57 | | } |
| 2 | 58 | | }; |
| 4 | 59 | | }); |
| 2 | 60 | | } |
| | 61 | | } |