75 lines
2.5 KiB
C#
75 lines
2.5 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using QMax.Api.Configuration;
|
|
using QMax.Api.Data.Entities;
|
|
|
|
namespace QMax.Api.Infrastructure.Auth;
|
|
|
|
public interface ITokenService
|
|
{
|
|
string CreateAccessToken(User user, UserSession session, DateTimeOffset expiresAt);
|
|
string CreateRefreshToken();
|
|
string HashRefreshToken(string refreshToken);
|
|
}
|
|
|
|
public sealed class TokenService(IOptions<QMaxOptions> options) : ITokenService
|
|
{
|
|
private readonly QMaxOptions _options = options.Value;
|
|
|
|
public string CreateAccessToken(User user, UserSession session, DateTimeOffset expiresAt)
|
|
{
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtSecret()));
|
|
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
var claims = new[]
|
|
{
|
|
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
|
new Claim("sid", session.Id.ToString()),
|
|
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
new Claim(ClaimTypes.Name, user.DisplayName)
|
|
};
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: _options.JwtIssuer,
|
|
audience: _options.JwtAudience,
|
|
claims: claims,
|
|
notBefore: DateTime.UtcNow,
|
|
expires: expiresAt.UtcDateTime,
|
|
signingCredentials: credentials);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
|
|
public string CreateRefreshToken()
|
|
{
|
|
Span<byte> bytes = stackalloc byte[48];
|
|
RandomNumberGenerator.Fill(bytes);
|
|
return Convert.ToBase64String(bytes);
|
|
}
|
|
|
|
public string HashRefreshToken(string refreshToken)
|
|
{
|
|
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken));
|
|
return Convert.ToHexString(bytes);
|
|
}
|
|
|
|
private string GetJwtSecret()
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(_options.JwtSecret) && _options.JwtSecret.Length >= 32)
|
|
{
|
|
return _options.JwtSecret;
|
|
}
|
|
|
|
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
|
|
{
|
|
return "development-only-qmax-secret-change-before-production";
|
|
}
|
|
|
|
throw new InvalidOperationException("QMax:JwtSecret must be set to at least 32 characters in production.");
|
|
}
|
|
}
|