IdentityHelpers.cs
1,794 bytes
| 1 | using System.IdentityModel.Tokens.Jwt; |
|---|---|
| 2 | using System.Security.Claims; |
| 3 | using System.Text; |
| 4 | using Microsoft.IdentityModel.Tokens; |
| 5 | |
| 6 | namespace SplitApp.Shared.Kernel.Auth; |
| 7 | |
| 8 | public static class IdentityHelpers |
| 9 | { |
| 10 | public static string GenerateJwt( |
| 11 | IEnumerable<Claim> claims, |
| 12 | string key, |
| 13 | string issuer, |
| 14 | string audience, |
| 15 | int expiresInSeconds) |
| 16 | { |
| 17 | var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)); |
| 18 | var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); |
| 19 | var expires = DateTime.UtcNow.AddSeconds(expiresInSeconds); |
| 20 | var token = new JwtSecurityToken( |
| 21 | issuer: issuer, |
| 22 | audience: audience, |
| 23 | claims: claims, |
| 24 | expires: expires, |
| 25 | signingCredentials: signingCredentials |
| 26 | ); |
| 27 | return new JwtSecurityTokenHandler().WriteToken(token); |
| 28 | } |
| 29 | |
| 30 | /// <summary> |
| 31 | /// Validate JWT token signature and issuer/audience. |
| 32 | /// Ignores expiration - used during token refresh where the JWT is allowed to be expired. |
| 33 | /// </summary> |
| 34 | public static bool ValidateJWT( |
| 35 | string jwt, |
| 36 | string key, |
| 37 | string issuer, |
| 38 | string audience) |
| 39 | { |
| 40 | var tokenHandler = new JwtSecurityTokenHandler(); |
| 41 | var validationParameters = new TokenValidationParameters |
| 42 | { |
| 43 | ValidIssuer = issuer, |
| 44 | ValidAudience = audience, |
| 45 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), |
| 46 | ValidateLifetime = false |
| 47 | }; |
| 48 | |
| 49 | try |
| 50 | { |
| 51 | tokenHandler.ValidateToken(jwt, validationParameters, out _); |
| 52 | return true; |
| 53 | } |
| 54 | catch (Exception) |
| 55 | { |
| 56 | return false; |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |