34 lines
1.1 KiB
C#
34 lines
1.1 KiB
C#
using System.Security.Cryptography;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
namespace GhostImageManager.Services;
|
|
|
|
public static class JwtTokenService
|
|
{
|
|
public static string GenerateToken(string adminApiKey)
|
|
{
|
|
var parts = adminApiKey.Split(':', 2);
|
|
if (parts.Length != 2)
|
|
throw new ArgumentException("Admin API Key muss im Format {id}:{secret} sein.");
|
|
|
|
string keyId = parts[0];
|
|
string secret = parts[1];
|
|
|
|
var now = DateTimeOffset.UtcNow;
|
|
var securityKey = new SymmetricSecurityKey(Convert.FromHexString(secret));
|
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
header: new JwtHeader(credentials) { { "kid", keyId } },
|
|
payload: new JwtPayload
|
|
{
|
|
{ "iat", now.ToUnixTimeSeconds() },
|
|
{ "exp", now.AddMinutes(5).ToUnixTimeSeconds() },
|
|
{ "aud", "/admin/" }
|
|
}
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|