Kavita/API/Services/TokenService.cs
Joe Milazzo 979508047c
v0.7.8 - New Filtering System (#2260)
Co-authored-by: JeanPaulDOT <jp.houssier@gmail.com>
Co-authored-by: Francois Wilhelmy <ice_mouton@hotmail.com>
Co-authored-by: Gazy Mahomar <gmahomarf@gmail.com>
Co-authored-by: Stijn <stijn.biemans@gmail.com>
Co-authored-by: 無情天 <kofzhanganguo@126.com>
Co-authored-by: Havokdan <havokdan@yahoo.com.br>
Co-authored-by: Andre <andruecha32@gmail.com>
Co-authored-by: Mateusz <mateuszvx8.96@gmail.com>
Co-authored-by: Antonio Sanchez Castellón <angelfx19@gmail.com>
Co-authored-by: Duarte Silva <smallflake@protonmail.com>
Co-authored-by: LeeWan1210 <dldhks456@live.com>
Co-authored-by: aleixcox <18121624@qq.com>
Co-authored-by: Tomas Battistini <tomas.battistini@gmail.com>
Co-authored-by: mareczek82 <marek.posiadala@gmail.com>
Co-authored-by: Hans Kalisvaart <hans.kalisvaart@gmail.com>
Co-authored-by: majora2007 <kavitareader@gmail.com>
Co-authored-by: afermar <adrian.fm@protonmail.com>
Co-authored-by: oxygen44k <iiccpp@outlook.com>
Co-authored-by: Weblate (bot) <hosted@weblate.org>
Co-authored-by: Hadrien b <hadrien.1997@gmail.com>
Co-authored-by: Robbie Davis <robbie@therobbiedavis.com>
Co-authored-by: Andre Smith <Hobogrammer@users.noreply.github.com>
Co-authored-by: Safu Wan <safu@yahoo.com>
Co-authored-by: sibeck <sibeck.clown@gmail.com>
Co-authored-by: Florestano Pepe <florestano.pepe@gmail.com>
Co-authored-by: 书签 <shuqian.emu@gmail.com>
Co-authored-by: Stéphane Dupont <aleistor@gmail.com>
Co-authored-by: gallegonovato <fran-carro@hotmail.es>
Co-authored-by: AlienHack <the4got10@windowslive.com>
Co-authored-by: 周書丞 <tmrsm_chan@hotmail.com>
Co-authored-by: Andre Smith <andrepsmithjr@gmail.com>
Co-authored-by: xe1st <dnzkckali@gmail.com>
Co-authored-by: Jiří Heger <jiri.heger@gmail.com>
Co-authored-by: DR <weblate-kavita.snowflake668@slmail.me>
Co-authored-by: Mathieu Ares <matguitarist@gmail.com>
Co-authored-by: Stavros Kois <47820033+stavros-k@users.noreply.github.com>
Co-authored-by: Gazy Mahomar <gmahomarf@users.noreply.github.com>
Co-authored-by: Elias Jakob <elias.jakob100@gmail.com>
Co-authored-by: Christian Zanon <chri8431@libero.it>
Co-authored-by: Eryk Michalak <gnu.ewm@protonmail.com>
Co-authored-by: Hoshino0881118 <hoshino0881118@gmail.com>
2023-09-03 12:31:50 -07:00

150 lines
5.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using API.Data;
using API.DTOs.Account;
using API.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using static System.Security.Claims.ClaimTypes;
using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames;
namespace API.Services;
public interface ITokenService
{
Task<string> CreateToken(AppUser user);
Task<TokenRequestDto?> ValidateRefreshToken(TokenRequestDto request);
Task<string> CreateRefreshToken(AppUser user);
Task<string> GetJwtFromUser(AppUser user);
bool HasTokenExpired(string token);
}
public class TokenService : ITokenService
{
private readonly UserManager<AppUser> _userManager;
private readonly ILogger<TokenService> _logger;
private readonly IUnitOfWork _unitOfWork;
private readonly SymmetricSecurityKey _key;
private const string RefreshTokenName = "RefreshToken";
public TokenService(IConfiguration config, UserManager<AppUser> userManager, ILogger<TokenService> logger, IUnitOfWork unitOfWork)
{
_userManager = userManager;
_logger = logger;
_unitOfWork = unitOfWork;
_key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"] ?? string.Empty));
}
public async Task<string> CreateToken(AppUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Name, user.UserName!),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
};
var roles = await _userManager.GetRolesAsync(user);
claims.AddRange(roles.Select(role => new Claim(Role, role)));
var credentials = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddDays(10),
SigningCredentials = credentials
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
public async Task<string> CreateRefreshToken(AppUser user)
{
await _userManager.RemoveAuthenticationTokenAsync(user, TokenOptions.DefaultProvider, RefreshTokenName);
var refreshToken = await _userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultProvider, RefreshTokenName);
await _userManager.SetAuthenticationTokenAsync(user, TokenOptions.DefaultProvider, RefreshTokenName, refreshToken);
return refreshToken;
}
public async Task<TokenRequestDto?> ValidateRefreshToken(TokenRequestDto request)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenContent = tokenHandler.ReadJwtToken(request.Token);
var username = tokenContent.Claims.FirstOrDefault(q => q.Type == JwtRegisteredClaimNames.Name)?.Value;
if (string.IsNullOrEmpty(username))
{
_logger.LogDebug("[RefreshToken] failed to validate due to not finding user in RefreshToken");
return null;
}
var user = await _userManager.FindByNameAsync(username);
if (user == null)
{
_logger.LogDebug("[RefreshToken] failed to validate due to not finding user in DB");
return null;
}
var validated = await _userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, RefreshTokenName, request.RefreshToken);
if (!validated && tokenContent.ValidTo <= DateTime.UtcNow.Add(TimeSpan.FromHours(1)))
{
_logger.LogDebug("[RefreshToken] failed to validate due to invalid refresh token");
return null;
}
try
{
user.UpdateLastActive();
_unitOfWork.UserRepository.Update(user);
await _unitOfWork.CommitAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "There was an error updating last active for the user");
}
return new TokenRequestDto()
{
Token = await CreateToken(user),
RefreshToken = await CreateRefreshToken(user)
};
} catch (SecurityTokenExpiredException ex)
{
// Handle expired token
_logger.LogError(ex, "Failed to validate refresh token");
return null;
}
catch (Exception ex)
{
// Handle other exceptions
_logger.LogError(ex, "Failed to validate refresh token");
return null;
}
}
public async Task<string> GetJwtFromUser(AppUser user)
{
var userClaims = await _userManager.GetClaimsAsync(user);
var jwtClaim = userClaims.FirstOrDefault(claim => claim.Type == "jwt");
return jwtClaim?.Value;
}
public bool HasTokenExpired(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenContent = tokenHandler.ReadJwtToken(token);
return tokenContent.ValidTo <= DateTime.UtcNow;
}
}