| | | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | | 2 | | using ArturRios.Jwt; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Configuration; |
| | | 4 | | using ArturRios.Util.WebApi.Security.Enums; |
| | | 5 | | using ArturRios.Util.WebApi.Security.Interfaces; |
| | | 6 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 7 | | using Microsoft.AspNetCore.Http; |
| | | 8 | | using Microsoft.Extensions.DependencyInjection; |
| | | 9 | | |
| | | 10 | | namespace ArturRios.Util.WebApi.Security.Authentication; |
| | | 11 | | |
| | | 12 | | /// <summary>Validates the app's own HMAC-signed JWT and resolves the user through the registered |
| | | 13 | | /// <see cref="IAuthenticatedUserMapper"/> — from claims alone or by an <see cref="IAuthenticationProvider"/> |
| | | 14 | | /// lookup, per <see cref="AuthenticationOptions.JwtMode"/>. The token's issuer and audience are checked against |
| | | 15 | | /// <see cref="JwtConfiguration.Issuer"/> and <see cref="JwtConfiguration.Audience"/> only when |
| | | 16 | | /// <see cref="AuthenticationOptions.ValidateIssuer"/> / <see cref="AuthenticationOptions.ValidateAudience"/> are on.</s |
| | | 17 | | public class JwtTokenValidator : ITokenValidator |
| | | 18 | | { |
| | 1 | 19 | | private static readonly JwtSecurityTokenHandler TokenReader = new(); |
| | | 20 | | |
| | | 21 | | private readonly JwtConfiguration _jwtConfig; |
| | | 22 | | private readonly JwtHandler _jwtHandler; |
| | | 23 | | private readonly IAuthenticatedUserMapper _mapper; |
| | | 24 | | private readonly AuthenticationOptions _options; |
| | | 25 | | |
| | | 26 | | /// <summary>Creates the validator.</summary> |
| | | 27 | | /// <param name="jwtConfig">Provides the key material used to validate the token, and the expected issuer and audien |
| | | 28 | | /// <param name="jwtHandler">Validates token signatures.</param> |
| | | 29 | | /// <param name="mapper">Interprets the token's claims as the app's user.</param> |
| | | 30 | | /// <param name="options">Controls the issuer/audience checks and how the user is resolved once the signature is val |
| | | 31 | | /// <exception cref="InvalidOperationException"><see cref="AuthenticationOptions.ValidateIssuer"/> is on and |
| | | 32 | | /// <see cref="JwtConfiguration.Issuer"/> is blank, or <see cref="AuthenticationOptions.ValidateAudience"/> is on an |
| | | 33 | | /// <see cref="JwtConfiguration.Audience"/> is blank.</exception> |
| | 57 | 34 | | public JwtTokenValidator( |
| | 57 | 35 | | JwtConfiguration jwtConfig, |
| | 57 | 36 | | JwtHandler jwtHandler, |
| | 57 | 37 | | IAuthenticatedUserMapper mapper, |
| | 57 | 38 | | AuthenticationOptions options) |
| | | 39 | | { |
| | | 40 | | // Checked here because the validator is created when AuthenticationMiddleware is built, at application |
| | | 41 | | // startup. A check that is on with nothing to compare against would otherwise reject every token at run |
| | | 42 | | // time instead of failing the misconfigured deployment. |
| | 57 | 43 | | EnsureExpectedValuesConfigured(jwtConfig, options); |
| | | 44 | | |
| | 51 | 45 | | _jwtConfig = jwtConfig; |
| | 51 | 46 | | _jwtHandler = jwtHandler; |
| | 51 | 47 | | _mapper = mapper; |
| | 51 | 48 | | _options = options; |
| | 51 | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <inheritdoc /> |
| | | 52 | | public async Task<TokenValidationResult> ValidateAsync(string token, HttpContext context) |
| | | 53 | | { |
| | | 54 | | // Every configured key when there are any, so a token signed with a key that is no longer |
| | | 55 | | // the signing key stays valid until it is withdrawn — which is what makes replacing a signing |
| | | 56 | | // secret a rotation rather than a cutover that invalidates every token in flight. Falls back |
| | | 57 | | // to the single secret when no keys are configured, which is what every configuration written |
| | | 58 | | // before ArturRios.Jwt 1.1.0 looks like. |
| | 44 | 59 | | var isValid = _jwtConfig.Keys.Count > 0 |
| | 44 | 60 | | ? await _jwtHandler.IsTokenValidAsync(token, _jwtConfig.Keys) |
| | 44 | 61 | | : await _jwtHandler.IsTokenValidAsync(token, _jwtConfig.Secret); |
| | | 62 | | |
| | 44 | 63 | | if (!isValid) |
| | | 64 | | { |
| | 10 | 65 | | return new TokenValidationResult(null, "Invalid token"); |
| | | 66 | | } |
| | | 67 | | |
| | | 68 | | // Only after the signature: before it, the claims are whatever the sender wrote. |
| | 34 | 69 | | var issuerAndAudienceError = CheckIssuerAndAudience(token); |
| | | 70 | | |
| | 34 | 71 | | if (issuerAndAudienceError is not null) |
| | | 72 | | { |
| | 9 | 73 | | return new TokenValidationResult(null, issuerAndAudienceError); |
| | | 74 | | } |
| | | 75 | | |
| | 25 | 76 | | var claims = TokenClaimsReader.Read(token); |
| | | 77 | | |
| | 25 | 78 | | if (claims is null) |
| | | 79 | | { |
| | 0 | 80 | | return new TokenValidationResult(null, "Could not read token claims"); |
| | | 81 | | } |
| | | 82 | | |
| | 25 | 83 | | if (_options.JwtMode == JwtValidationMode.ClaimsOnly) |
| | | 84 | | { |
| | 20 | 85 | | var claimsUser = MapUser(claims); |
| | | 86 | | |
| | 20 | 87 | | return new TokenValidationResult(claimsUser, claimsUser is null ? "Could not retrieve user from token" : nul |
| | | 88 | | } |
| | | 89 | | |
| | 5 | 90 | | var userId = MapId(claims); |
| | | 91 | | |
| | 5 | 92 | | if (userId is null) |
| | | 93 | | { |
| | 2 | 94 | | return new TokenValidationResult(null, "Could not retrieve user id from token"); |
| | | 95 | | } |
| | | 96 | | |
| | 3 | 97 | | var provider = context.RequestServices.GetRequiredService<IAuthenticationProvider>(); |
| | 3 | 98 | | var user = provider.GetAuthenticatedUserById(userId.Value); |
| | | 99 | | |
| | 3 | 100 | | return new TokenValidationResult(user, user is null ? "User not found" : null); |
| | 44 | 101 | | } |
| | | 102 | | |
| | | 103 | | private string? CheckIssuerAndAudience(string token) |
| | | 104 | | { |
| | 34 | 105 | | if (!_options.ValidateIssuer && !_options.ValidateAudience) |
| | | 106 | | { |
| | 21 | 107 | | return null; |
| | | 108 | | } |
| | | 109 | | |
| | | 110 | | JwtSecurityToken jwt; |
| | | 111 | | |
| | | 112 | | try |
| | | 113 | | { |
| | 13 | 114 | | jwt = TokenReader.ReadJwtToken(token); |
| | 13 | 115 | | } |
| | 0 | 116 | | catch (Exception) |
| | | 117 | | { |
| | 0 | 118 | | return "Could not read token claims"; |
| | | 119 | | } |
| | | 120 | | |
| | 13 | 121 | | if (_options.ValidateIssuer && !string.Equals(jwt.Issuer, _jwtConfig.Issuer, StringComparison.Ordinal)) |
| | | 122 | | { |
| | 5 | 123 | | return "Invalid token issuer"; |
| | | 124 | | } |
| | | 125 | | |
| | 8 | 126 | | if (_options.ValidateAudience && !jwt.Audiences.Contains(_jwtConfig.Audience, StringComparer.Ordinal)) |
| | | 127 | | { |
| | 4 | 128 | | return "Invalid token audience"; |
| | | 129 | | } |
| | | 130 | | |
| | 4 | 131 | | return null; |
| | 0 | 132 | | } |
| | | 133 | | |
| | | 134 | | private static void EnsureExpectedValuesConfigured(JwtConfiguration jwtConfig, AuthenticationOptions options) |
| | | 135 | | { |
| | 57 | 136 | | if (options.ValidateIssuer && string.IsNullOrWhiteSpace(jwtConfig.Issuer)) |
| | | 137 | | { |
| | 3 | 138 | | throw new InvalidOperationException( |
| | 3 | 139 | | "AuthenticationOptions.ValidateIssuer is on, but JwtConfiguration.Issuer is empty. Configure the " + |
| | 3 | 140 | | "issuer the app's tokens are minted with, or turn ValidateIssuer off."); |
| | | 141 | | } |
| | | 142 | | |
| | 54 | 143 | | if (options.ValidateAudience && string.IsNullOrWhiteSpace(jwtConfig.Audience)) |
| | | 144 | | { |
| | 3 | 145 | | throw new InvalidOperationException( |
| | 3 | 146 | | "AuthenticationOptions.ValidateAudience is on, but JwtConfiguration.Audience is empty. Configure " + |
| | 3 | 147 | | "the audience the app's tokens are minted for, or turn ValidateAudience off."); |
| | | 148 | | } |
| | 51 | 149 | | } |
| | | 150 | | |
| | | 151 | | private IAuthenticatedUser? MapUser(IReadOnlyDictionary<string, string> claims) |
| | | 152 | | { |
| | | 153 | | try |
| | | 154 | | { |
| | 20 | 155 | | return _mapper.FromClaims(claims); |
| | | 156 | | } |
| | 1 | 157 | | catch (Exception) |
| | | 158 | | { |
| | 1 | 159 | | return null; |
| | | 160 | | } |
| | 20 | 161 | | } |
| | | 162 | | |
| | | 163 | | private Guid? MapId(IReadOnlyDictionary<string, string> claims) |
| | | 164 | | { |
| | | 165 | | try |
| | | 166 | | { |
| | 5 | 167 | | return _mapper.IdFromClaims(claims); |
| | | 168 | | } |
| | 1 | 169 | | catch (Exception) |
| | | 170 | | { |
| | 1 | 171 | | return null; |
| | | 172 | | } |
| | 5 | 173 | | } |
| | | 174 | | } |