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