Files
Govor/Govor.Application/Services/Authentication/JwtService.cs
T
Artemy ab643c16a4 Implement user session management and JWT refresh tokens
Added user session models, interfaces, repository, and service for managing user sessions and refresh tokens. Refactored authentication flow to return user objects and open sessions with device info, supporting refresh token generation and validation. Updated JWT configuration to separate access and refresh options, and refactored related tests and API contracts. Improved media upload handling and error logging. Migrated dependency references and DI registrations accordingly.
2025-07-18 20:16:36 +07:00

84 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Govor.Application.Interfaces.Authentication;
using Govor.Core.Models.Users;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Govor.Application.Services.Authentication;
public class JwtService : IJwtService
{
private JwtAccessOption _jwtAccessOption;
private JwtRefreshOption _refreshOptions;
private IInvitesService _invitesService;
public JwtService(IOptions<JwtAccessOption> options, IOptions<JwtRefreshOption> refreshOptions, IInvitesService invitesService)
{
_refreshOptions = refreshOptions.Value;
_jwtAccessOption = options.Value;
_invitesService = invitesService;
}
public async Task<string> GenerateAccessTokenAsync(User user)
{
var claims = new[]
{
new Claim("userId", user.Id.ToString()),
new Claim(ClaimTypes.Role, await _invitesService.GetRoleAsync(user), ClaimValueTypes.String)
};
var singing = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу)),
SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
expires: DateTime.UtcNow.AddMinutes(_jwtAccessOption.Minutes),
signingCredentials: singing,
claims: claims);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public async Task<string> GenerateRefreshTokenAsync(User user)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim("userId", user.Id.ToString()),
new Claim("tokenType", "refresh")
};
var token = new JwtSecurityToken(
expires: DateTime.UtcNow.AddDays(_refreshOptions.RefreshTokenLifetimeDays),
signingCredentials: creds,
claims: claims
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу)),
ValidateLifetime = false // << important
};
var handler = new JwtSecurityTokenHandler();
var principal = handler.ValidateToken(token, tokenValidationParameters, out var securityToken);
if (securityToken is not JwtSecurityToken jwtToken || jwtToken.Header.Alg != SecurityAlgorithms.HmacSha256)
throw new SecurityTokenException("Invalid token");
return principal;
}
}