| | 1 | | using System.IdentityModel.Tokens.Jwt; |
| | 2 | |
|
| | 3 | | namespace Kestrun.Jwt; |
| | 4 | | /// <summary> |
| | 5 | | /// Provides methods for inspecting and extracting parameters from JWT tokens. |
| | 6 | | /// </summary> |
| | 7 | | public static class JwtInspector |
| | 8 | | { |
| | 9 | | /// <summary> |
| | 10 | | /// Reads out every header field, standard property, and claim from a compact JWT. |
| | 11 | | /// </summary> |
| | 12 | | public static JwtParameters ReadAllParameters(string token) |
| | 13 | | { |
| 10 | 14 | | var handler = new JwtSecurityTokenHandler(); |
| | 15 | |
|
| | 16 | | // parse without validating signature or lifetime |
| 10 | 17 | | var jwt = handler.ReadJwtToken(token); |
| | 18 | |
|
| 10 | 19 | | var result = new JwtParameters |
| 10 | 20 | | { |
| 10 | 21 | | Issuer = jwt.Issuer, |
| 10 | 22 | | Audiences = jwt.Audiences, |
| 10 | 23 | | Subject = jwt.Subject, |
| 10 | 24 | | NotBefore = jwt.ValidFrom == DateTime.MinValue ? null : jwt.ValidFrom, |
| 10 | 25 | | Expires = jwt.ValidTo == DateTime.MinValue ? null : jwt.ValidTo, |
| 10 | 26 | | IssuedAt = jwt.Payload.IssuedAt == DateTime.MinValue ? null : jwt.Payload.IssuedAt, |
| 10 | 27 | | Algorithm = jwt.SignatureAlgorithm, |
| 10 | 28 | | Type = jwt.Header.Typ, |
| 10 | 29 | | KeyId = jwt.Header.Kid |
| 10 | 30 | | }; |
| | 31 | |
|
| | 32 | | // copy all header entries |
| 88 | 33 | | foreach (var kv in jwt.Header) |
| | 34 | | { |
| 34 | 35 | | result.Header[kv.Key] = kv.Value!; |
| | 36 | | } |
| | 37 | |
|
| | 38 | | // copy all payload claims (including custom ones) |
| 158 | 39 | | foreach (var claim in jwt.Claims) |
| | 40 | | { |
| | 41 | | // if a claim type can appear multiple times, you might want to handle lists |
| 69 | 42 | | result.Claims[claim.Type] = claim.Value; |
| | 43 | | } |
| | 44 | |
|
| 10 | 45 | | return result; |
| | 46 | | } |
| | 47 | | } |