| | | 1 | | using ArturRios.Jwt; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Configuration; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Enums; |
| | | 4 | | using ArturRios.Util.WebApi.Security.Factories; |
| | | 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 by claims or by an <see cref="IAuthentication |
| | | 13 | | /// <param name="jwtConfig">Provides the signing secret used to validate the token.</param> |
| | | 14 | | /// <param name="jwtHandler">Validates signatures and reads the user id claim.</param> |
| | | 15 | | /// <param name="options">Controls how the user is resolved once the signature is valid.</param> |
| | 10 | 16 | | public class JwtTokenValidator(JwtConfiguration jwtConfig, JwtHandler jwtHandler, AuthenticationOptions options) : IToke |
| | | 17 | | { |
| | | 18 | | /// <inheritdoc /> |
| | | 19 | | public async Task<TokenValidationResult> ValidateAsync(string token, HttpContext context) |
| | 9 | 20 | | { |
| | 9 | 21 | | var isValid = await jwtHandler.IsTokenValidAsync(token, jwtConfig.Secret); |
| | | 22 | | |
| | 9 | 23 | | if (!isValid) |
| | 3 | 24 | | { |
| | 3 | 25 | | return new TokenValidationResult(null, "Invalid token"); |
| | | 26 | | } |
| | | 27 | | |
| | 6 | 28 | | if (options.JwtMode == JwtValidationMode.ClaimsOnly) |
| | 4 | 29 | | { |
| | 4 | 30 | | var claimsUser = AuthenticatedUserFactory.FromToken(token); |
| | | 31 | | |
| | 4 | 32 | | return new TokenValidationResult(claimsUser, claimsUser is null ? "Could not retrieve user from token" : nul |
| | | 33 | | } |
| | | 34 | | |
| | 2 | 35 | | var userId = jwtHandler.GetUserIdFromToken(token); |
| | | 36 | | |
| | 2 | 37 | | if (!userId.HasValue) |
| | 0 | 38 | | { |
| | 0 | 39 | | return new TokenValidationResult(null, "Could not retrieve user id from token"); |
| | | 40 | | } |
| | | 41 | | |
| | 2 | 42 | | var provider = context.RequestServices.GetRequiredService<IAuthenticationProvider>(); |
| | 2 | 43 | | var user = provider.GetAuthenticatedUserById(userId.Value); |
| | | 44 | | |
| | 2 | 45 | | return new TokenValidationResult(user, user is null ? "User not found" : null); |
| | 9 | 46 | | } |
| | | 47 | | } |