| | | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | | 2 | | using ArturRios.Util.WebApi.Security.Constants; |
| | | 3 | | using ArturRios.Util.WebApi.Security.Records; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.WebApi.Security.Factories; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Reconstructs an <see cref="AuthenticatedUser"/> from the claims embedded in a JSON Web Token, |
| | | 9 | | /// without hitting any data store. Callers must validate the token's signature before trusting the result. |
| | | 10 | | /// </summary> |
| | | 11 | | public static class AuthenticatedUserFactory |
| | | 12 | | { |
| | 1 | 13 | | private static readonly JwtSecurityTokenHandler Handler = new(); |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Builds an <see cref="AuthenticatedUser"/> from the token's <c>id</c> and <c>role</c> claims. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="token">The JWT to read. Its signature is not validated here.</param> |
| | | 19 | | /// <returns> |
| | | 20 | | /// The reconstructed user, or <see langword="null"/> if the token cannot be read or is missing a |
| | | 21 | | /// numeric <c>id</c> or <c>role</c> claim. |
| | | 22 | | /// </returns> |
| | | 23 | | public static AuthenticatedUser? FromToken(string token) |
| | 7 | 24 | | { |
| | 7 | 25 | | if (string.IsNullOrWhiteSpace(token) || !Handler.CanReadToken(token)) |
| | 2 | 26 | | { |
| | 2 | 27 | | return null; |
| | | 28 | | } |
| | | 29 | | |
| | 5 | 30 | | var claims = Handler.ReadJwtToken(token).Claims.ToArray(); |
| | | 31 | | |
| | 10 | 32 | | var idClaim = claims.FirstOrDefault(claim => claim.Type == TokenClaimKeys.Id)?.Value; |
| | 15 | 33 | | var roleClaim = claims.FirstOrDefault(claim => claim.Type == TokenClaimKeys.Role)?.Value; |
| | | 34 | | |
| | 5 | 35 | | if (!int.TryParse(idClaim, out var id) || !int.TryParse(roleClaim, out var role)) |
| | 0 | 36 | | { |
| | 0 | 37 | | return null; |
| | | 38 | | } |
| | | 39 | | |
| | 5 | 40 | | return new AuthenticatedUser(id, role); |
| | 7 | 41 | | } |
| | | 42 | | } |