Add: JWT authentication in Web API. Related configuration and services are added.
44 lines
1.6 KiB
C#
44 lines
1.6 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<OptixServeSettings> optixServeSettings) : ITokenService
|
|
{
|
|
private readonly JwtSettings _jwtSettings = optixServeSettings.Value.Jwt ?? throw new ArgumentNullException(nameof(optixServeSettings), "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);
|
|
}
|
|
} |