| | | 1 | | using System.Security.Claims; |
| | | 2 | | using Microsoft.IdentityModel.Tokens; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.Authentication; |
| | | 5 | | /// <summary> |
| | | 6 | | /// Service to create OpenID Connect client assertions. |
| | | 7 | | /// </summary> |
| | | 8 | | public class AssertionService |
| | | 9 | | { |
| | | 10 | | private readonly JsonWebKey _jwk; |
| | | 11 | | private readonly SigningCredentials _credentials; |
| | | 12 | | private readonly string _clientId; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Gets the Client ID. |
| | | 16 | | /// </summary> |
| | 0 | 17 | | public string ClientId => _clientId; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance of the <see cref="AssertionService"/> class. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="clientId">The client identifier.</param> |
| | | 23 | | /// <param name="jwkJson"></param> |
| | 12 | 24 | | public AssertionService(string clientId, string? jwkJson) |
| | | 25 | | { |
| | 12 | 26 | | _clientId = clientId; |
| | 12 | 27 | | _jwk = new JsonWebKey(jwkJson); |
| | 12 | 28 | | _credentials = new SigningCredentials(_jwk, SecurityAlgorithms.RsaSha256); |
| | 12 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Creates a client assertion for the specified token endpoint. |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="tokenEndpoint"> The token endpoint for which the assertion is created.</param> |
| | | 35 | | /// <returns></returns> |
| | | 36 | | public string CreateClientAssertion(string tokenEndpoint) |
| | | 37 | | { |
| | 12 | 38 | | var now = DateTime.UtcNow; |
| | | 39 | | |
| | 12 | 40 | | var claims = new List<Claim> |
| | 12 | 41 | | { |
| | 12 | 42 | | new("iss", _clientId), |
| | 12 | 43 | | new("sub", _clientId), |
| | 12 | 44 | | new(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), |
| | 12 | 45 | | new(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Iat, |
| | 12 | 46 | | new DateTimeOffset(now).ToUnixTimeSeconds().ToString(), |
| | 12 | 47 | | ClaimValueTypes.Integer64) |
| | 12 | 48 | | }; |
| | | 49 | | |
| | 12 | 50 | | var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken( |
| | 12 | 51 | | issuer: _clientId, |
| | 12 | 52 | | audience: tokenEndpoint, |
| | 12 | 53 | | claims: claims, |
| | 12 | 54 | | notBefore: now, |
| | 12 | 55 | | expires: now.AddMinutes(1), |
| | 12 | 56 | | signingCredentials: _credentials); |
| | | 57 | | |
| | 12 | 58 | | return new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(token); |
| | | 59 | | } |
| | | 60 | | } |