- Remove unused using directives across C# and Razor files - Remove unused IServiceProvider from SettingsRepository - Simplify null/empty string checks in StatsRepository - Add null-safe navigation for Albums/Tags in stats queries - Initialize Asset.Hash default to prevent null refs - Deduplicate AssetIds in AssetPicker - Add OnStartedWaiting/OnFinishedWaiting/OnProgressChanged to Job - Add global SearchDropdown component with keyboard nav - Fix XML doc param mismatches
56 lines
2.0 KiB
C#
56 lines
2.0 KiB
C#
using Lactose.Configuration;
|
|
using Lactose.Utils;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
|
|
namespace Lactose.Services;
|
|
|
|
/// <summary>
|
|
/// Defines the contract for generating JWT tokens.
|
|
/// </summary>
|
|
public interface ITokenService {
|
|
/// <summary>
|
|
/// Generates a JWT token with the specified claims and expiration time.
|
|
/// </summary>
|
|
/// <param name="identity">The claims identity to include in the token.</param>
|
|
/// <param name="expireTime">The expiration time in minutes.</param>
|
|
/// <returns>A JWT token string.</returns>
|
|
string GenerateToken(ClaimsIdentity identity, int expireTime);
|
|
/// <summary>
|
|
/// Generates a JWT token with no additional claims and the specified expiration time.
|
|
/// </summary>
|
|
/// <param name="expireTime">The expiration time in minutes.</param>
|
|
/// <returns>A JWT token string.</returns>
|
|
string GenerateToken(int expireTime);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generates JWT tokens using a signing key from configuration.
|
|
/// </summary>
|
|
public class TokenService (
|
|
IOptions<SignKeyConfiguration> signKey
|
|
) : ITokenService {
|
|
|
|
/// <summary>
|
|
/// The default base expiration time for tokens in minutes.
|
|
/// </summary>
|
|
public const int BaseExpirationTime = 30;
|
|
|
|
readonly TokenGenerator tokenGenerator = new TokenGenerator(
|
|
new SigningCredentials(signKey.Value.GetSecurityKey(), SecurityAlgorithms.HmacSha256Signature),
|
|
descriptor => {
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var token = handler.CreateToken(descriptor);
|
|
return handler.WriteToken(token);
|
|
}
|
|
);
|
|
|
|
/// <inheritdoc />
|
|
public string GenerateToken(ClaimsIdentity identity, int expireTime = BaseExpirationTime) => tokenGenerator.Generate(identity, expireTime);
|
|
|
|
/// <inheritdoc />
|
|
public string GenerateToken(int expireTime = BaseExpirationTime) => tokenGenerator.Generate(expireTime);
|
|
}
|