Add JWT authentication.
Add: JWT authentication in Web API. Related configuration and services are added.
This commit is contained in:
44
OptixServe.Api/Services/TokenService.cs
Normal file
44
OptixServe.Api/Services/TokenService.cs
Normal file
@ -0,0 +1,44 @@
|
||||
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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user