| | | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | | 2 | | |
| | | 3 | | namespace ArturRios.Util.WebApi.Security.Authentication; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Reads a JSON Web Token's claims into a dictionary, without validating its signature. Callers must |
| | | 7 | | /// validate the signature before trusting the result. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class TokenClaimsReader |
| | | 10 | | { |
| | 1 | 11 | | private static readonly JwtSecurityTokenHandler Handler = new(); |
| | | 12 | | |
| | | 13 | | /// <summary>Reads the token's claims. A repeated claim key keeps its first occurrence.</summary> |
| | | 14 | | /// <param name="token">The JWT to read. Its signature is not validated here.</param> |
| | | 15 | | /// <returns>The token's claims, or <see langword="null"/> if the token is blank or cannot be read.</returns> |
| | | 16 | | public static IReadOnlyDictionary<string, string>? Read(string token) |
| | | 17 | | { |
| | 23 | 18 | | if (string.IsNullOrWhiteSpace(token) || !Handler.CanReadToken(token)) |
| | | 19 | | { |
| | 2 | 20 | | return null; |
| | | 21 | | } |
| | | 22 | | |
| | | 23 | | JwtSecurityToken jwt; |
| | | 24 | | |
| | | 25 | | try |
| | | 26 | | { |
| | 21 | 27 | | jwt = Handler.ReadJwtToken(token); |
| | 20 | 28 | | } |
| | 1 | 29 | | catch (Exception) |
| | | 30 | | { |
| | 1 | 31 | | return null; |
| | | 32 | | } |
| | | 33 | | |
| | 20 | 34 | | var claims = new Dictionary<string, string>(); |
| | | 35 | | |
| | 310 | 36 | | foreach (var claim in jwt.Claims) |
| | | 37 | | { |
| | 135 | 38 | | claims.TryAdd(claim.Type, claim.Value); |
| | | 39 | | } |
| | | 40 | | |
| | 20 | 41 | | return claims; |
| | 1 | 42 | | } |
| | | 43 | | } |