|
| 1 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 2 | +using Microsoft.IdentityModel.Tokens; |
| 3 | +using StrDss.Common; |
| 4 | +using StrDss.Model; |
| 5 | +using StrDss.Service; |
| 6 | +using System.IdentityModel.Tokens.Jwt; |
| 7 | +using System.Security.Cryptography; |
| 8 | + |
| 9 | +namespace StrDss.Api.Authentication |
| 10 | +{ |
| 11 | + public class ApsJwtBearerEvents : JwtBearerEvents |
| 12 | + { |
| 13 | + private ICurrentUser _currentUser; |
| 14 | + private IUserService _userService; |
| 15 | + private IRoleService _roleService; |
| 16 | + private readonly ILogger<StrDssLogger> _logger; |
| 17 | + private readonly IMemoryCacheService _memoryCache; |
| 18 | + |
| 19 | + public ApsJwtBearerEvents(ICurrentUser currentUser, IUserService userService, IRoleService roleService, ILogger<StrDssLogger> logger, IMemoryCacheService memoryCache) : base() |
| 20 | + { |
| 21 | + _currentUser = currentUser; |
| 22 | + _userService = userService; |
| 23 | + _roleService = roleService; |
| 24 | + _logger = logger; |
| 25 | + _memoryCache = memoryCache; |
| 26 | + } |
| 27 | + |
| 28 | + public override async Task TokenValidated(TokenValidatedContext context) |
| 29 | + { |
| 30 | + _currentUser.LoadApsSession(context!.Principal!); |
| 31 | + |
| 32 | + var (user, permissions) = await _userService.GetUserByGuidAsync(_currentUser.UserGuid); |
| 33 | + |
| 34 | + if (user == null) |
| 35 | + { |
| 36 | + var errorMessage = $"{_currentUser.DisplayName} is not registered."; |
| 37 | + context.Response.StatusCode = 401; |
| 38 | + context.Fail($"Unauthorized: {errorMessage}"); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + _currentUser.Id = user.UserIdentityId; |
| 43 | + _currentUser.IsActive = user.IsEnabled; |
| 44 | + _currentUser.AccessRequestStatus = user.AccessRequestStatusCd; |
| 45 | + _currentUser.AccessRequestRequired = _currentUser.AccessRequestStatus == AccessRequestStatuses.Denied; |
| 46 | + _currentUser.OrganizationType = user.RepresentedByOrganization?.OrganizationType ?? ""; |
| 47 | + _currentUser.OrganizationId = user.RepresentedByOrganizationId ?? 0; |
| 48 | + _currentUser.OrganizationName = user.RepresentedByOrganization?.OrganizationNm ?? ""; |
| 49 | + _currentUser.TermsAcceptanceDtm = user.TermsAcceptanceDtm; |
| 50 | + |
| 51 | + if (user.IsEnabled) |
| 52 | + { |
| 53 | + _currentUser.Permissions = permissions; |
| 54 | + |
| 55 | + foreach (var permission in permissions) |
| 56 | + { |
| 57 | + _currentUser.AddClaim(context!.Principal!, StrDssClaimTypes.Permission, permission); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if (!context.Request.Headers.TryGetValue("GW-JWT", out var jwtToken)) |
| 62 | + { |
| 63 | + _logger.LogWarning($"{_currentUser.UserName}: GW-JWT is missing"); |
| 64 | + context.Response.StatusCode = 401; |
| 65 | + context.Fail("Unauthorized"); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + var publicKey = await _memoryCache.GetPublicKeyAsync(false); |
| 70 | + var gwJwt = jwtToken.ToString(); |
| 71 | + |
| 72 | + if (gwJwt.IsEmpty()) |
| 73 | + { |
| 74 | + _logger.LogWarning($"{_currentUser.UserName}: GW-JWT is empty"); |
| 75 | + context.Response.StatusCode = 401; |
| 76 | + context.Fail("Unauthorized"); |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + if (!ValidateJwtToken(gwJwt, publicKey)) |
| 81 | + { |
| 82 | + publicKey = await _memoryCache.GetPublicKeyAsync(true); |
| 83 | + |
| 84 | + if (!ValidateJwtToken(gwJwt, publicKey)) |
| 85 | + { |
| 86 | + _logger.LogWarning($"{_currentUser.UserName}: GW-JWT is invalid"); |
| 87 | + context.Response.StatusCode = 401; |
| 88 | + context.Fail("Unauthorized"); |
| 89 | + return; |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private static bool ValidateJwtToken(string jwtToken, JsonWebKey publicKey) |
| 95 | + { |
| 96 | + var validationParameters = new TokenValidationParameters |
| 97 | + { |
| 98 | + ValidateIssuer = false, |
| 99 | + ValidateAudience = false, |
| 100 | + IssuerSigningKey = new RsaSecurityKey(new RSAParameters |
| 101 | + { |
| 102 | + Modulus = Base64UrlEncoder.DecodeBytes(publicKey.N), |
| 103 | + Exponent = Base64UrlEncoder.DecodeBytes(publicKey.E) |
| 104 | + }), |
| 105 | + ValidateLifetime = true, |
| 106 | + }; |
| 107 | + |
| 108 | + var handler = new JwtSecurityTokenHandler(); |
| 109 | + try |
| 110 | + { |
| 111 | + SecurityToken validatedToken; |
| 112 | + handler.ValidateToken(jwtToken, validationParameters, out validatedToken); |
| 113 | + return true; |
| 114 | + } |
| 115 | + catch (SecurityTokenException) |
| 116 | + { |
| 117 | + return false; |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | +} |
0 commit comments