Files
OptixServe/OptixServe.Api/Services/TokenService.cs
Huxley Deng 8b18de1735 BRAKING refactor project structure.
Refactor: the project is now divided into a more clear structure, with **Infrastructure** and **Application** layers added.

Refactor: configurations are split into sections for different layers.

Fix: now EF Core related operations, such as migration, should be invoked in `OptixServe.Infrastructure`, with config file and data dir passed into `dotnet ef` command. See `OptixServe.Infrastructure/Utilites/DesignTimeDbContextFactory.cs` for details.

Fix: EF migrations are ignored in gitignore on purpose in early development.
2025-07-11 14:48:50 +08:00

45 lines
1.5 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using OptixServe.Api.Configuration;
using OptixServe.Core.Models;
namespace OptixServe.Api.Services;
public interface ITokenService
{
public string GenerateToken(User user);
}
public class TokenService(IOptions<ApiConfiguration> apiConfiguration) : ITokenService
{
private readonly JwtSettings _jwtSettings = apiConfiguration.Value.Jwt ?? throw new ArgumentNullException(nameof(apiConfiguration), "JWT settings are not configured.");
public string GenerateToken(User user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
var claims = new List<Claim>
{
new (ClaimTypes.NameIdentifier, user.Id.ToString()),
new (ClaimTypes.Name, user.UserName)
// Add roles if applicable: new Claim(ClaimTypes.Role, user.Role)
};
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddMinutes(_jwtSettings.TokenExpirationMinutes),
Issuer = _jwtSettings.Issuer,
Audience = _jwtSettings.Audience,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}