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.
This commit is contained in:
Artemy
2025-07-18 20:16:36 +07:00
parent 6063aafd9e
commit ab643c16a4
48 changed files with 1860 additions and 84 deletions
@@ -30,7 +30,7 @@ public class AuthService : IAccountService
_usernameValidator = usernameValidator;
}
public async Task<string> RegistrationAsync(string name, string password, Invitation invitation)
public async Task<User> RegistrationAsync(string name, string password, Invitation invitation)
{
_usernameValidator.Validate(name);
@@ -55,11 +55,11 @@ public class AuthService : IAccountService
await SetRole(user, invitation);
return await _jwtService.GenerateJwtTokenAsync(user);
return user;
}
public async Task<string> LoginAsync(string name, string password)
public async Task<User> LoginAsync(string name, string password)
{
if (await _usersRepository.ExistsUsernameAsync(name) == false)
throw new UserNotRegisteredException(name);
@@ -69,9 +69,34 @@ public class AuthService : IAccountService
if (_passwordHasher.Verify(password, user.PasswordHash) == false)
throw new LoginUserException();
return await _jwtService.GenerateJwtTokenAsync(user);
return user;
}
/*
public async Task<string> RefreshTokenAsync(string refreshToken)
{
try
{
var principal = _jwtService.GetPrincipalFromExpiredToken(refreshToken);
var userId = Guid.Parse(principal?.FindFirst("userId")?.Value ?? string.Empty);
var storedTokens = await _userSessionsRepository.GetUserTokensAsync(userId);
if (!storedTokens.Contains(refreshToken))
throw new UnauthorizedAccessException("Invalid refresh token");
var user = await _usersRepository.FindByIdAsync(userId);
var newAccessToken = await _jwtService.GenerateAccessTokenAsync(user);
return newAccessToken;
}
catch (SecurityTokenException ex)
{
throw new InvalidOperationException("Invalid refresh token", ex);
}
}
*/
private async Task SetRole(User user, Invitation invitation)
{
if(invitation.IsAdmin)
@@ -1,6 +1,6 @@
namespace Govor.Application.Services.Authentication;
public class JwtOption
public class JwtAccessOption
{
public string SecretKeу {get; set;}
public int Hours { get; set; }
public int Minutes { get; set; }
}
@@ -0,0 +1,6 @@
namespace Govor.Application.Services.Authentication;
public class JwtRefreshOption
{
public int RefreshTokenLifetimeDays { get; set; }
}
@@ -1,7 +1,6 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Govor.API.Services.Authentication.Interfaces;
using Govor.Application.Interfaces.Authentication;
using Govor.Core.Models.Users;
using Microsoft.Extensions.Options;
@@ -11,16 +10,18 @@ namespace Govor.Application.Services.Authentication;
public class JwtService : IJwtService
{
private JwtOption _jwtOption;
private JwtAccessOption _jwtAccessOption;
private JwtRefreshOption _refreshOptions;
private IInvitesService _invitesService;
public JwtService(IOptions<JwtOption> options, IInvitesService invitesService)
public JwtService(IOptions<JwtAccessOption> options, IOptions<JwtRefreshOption> refreshOptions, IInvitesService invitesService)
{
_jwtOption = options.Value;
_refreshOptions = refreshOptions.Value;
_jwtAccessOption = options.Value;
_invitesService = invitesService;
}
public async Task<string> GenerateJwtTokenAsync(User user)
public async Task<string> GenerateAccessTokenAsync(User user)
{
var claims = new[]
{
@@ -29,13 +30,55 @@ public class JwtService : IJwtService
};
var singing = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SecretKeу)),
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtAccessOption.SecretKeу)),
SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(signingCredentials: singing,
expires: DateTime.UtcNow.AddHours(_jwtOption.Hours),
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;
}
}