41 lines
1.6 KiB
C#
41 lines
1.6 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace DigitalData.Core.Application
|
|
{
|
|
/// <summary>
|
|
/// Defines the operations for JWT service handling claims of type <typeparamref name="TClaimValue"/>.
|
|
/// </summary>
|
|
public interface IJWTService<TClaimValue>
|
|
{
|
|
/// <summary>
|
|
/// Generates a symmetric security key with the specified byte size.
|
|
/// </summary>
|
|
/// <param name="byteSize">The size of the security key in bytes. Default is 32 bytes.</param>
|
|
/// <returns>A new instance of <see cref="SymmetricSecurityKey"/>.</returns>
|
|
public static SymmetricSecurityKey GenerateSecurityKey(int byteSize = 32)
|
|
{
|
|
using var rng = RandomNumberGenerator.Create();
|
|
var randomBytes = new byte[byteSize];
|
|
rng.GetBytes(randomBytes);
|
|
var securityKey = new SymmetricSecurityKey(randomBytes);
|
|
|
|
return securityKey;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generates a token based on the specified claim value.
|
|
/// </summary>
|
|
/// <param name="claimValue">The claim value to encode in the token.</param>
|
|
/// <returns>A JWT as a string.</returns>
|
|
string GenerateToken(TClaimValue claimValue);
|
|
|
|
/// <summary>
|
|
/// Reads and validates a security token from a string representation.
|
|
/// </summary>
|
|
/// <param name="token">The JWT to read.</param>
|
|
/// <returns>A <see cref="JwtSecurityToken"/> if the token is valid; otherwise, null.</returns>
|
|
JwtSecurityToken? ReadSecurityToken(string token);
|
|
}
|
|
} |