Rename projects to FileShare
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
using FileShare_EFCore.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace FileShare_API.Authentication
|
||||
{
|
||||
/// <summary>
|
||||
/// JWT Token 服务,负责创建包含用户声明和角色的 Access Token。
|
||||
/// </summary>
|
||||
public sealed class JwtTokenService(IOptions<JwtOptions> options)
|
||||
{
|
||||
/// <summary>
|
||||
/// JWT 配置选项。
|
||||
/// </summary>
|
||||
private readonly JwtOptions _options = options.Value;
|
||||
|
||||
/// <summary>
|
||||
/// 创建包含用户声明和角色的 JWT Access Token。
|
||||
/// </summary>
|
||||
/// <param name="user">用户实体。</param>
|
||||
/// <param name="roles">角色集合。</param>
|
||||
/// <returns>包含 Token 字符串和过期时间的元组。</returns>
|
||||
public (string Token, DateTime ExpiresAt) CreateAccessToken(UserEntity user, IReadOnlyCollection<string> roles)
|
||||
{
|
||||
var expiresAt = DateTime.UtcNow.AddMinutes(_options.AccessTokenMinutes);
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new(ClaimTypes.Name, user.Name ?? user.Email ?? $"user-{user.Id}"),
|
||||
new("auth_type", "api-jwt"),
|
||||
};
|
||||
|
||||
foreach (var role in roles.Where(role => !string.IsNullOrWhiteSpace(role)).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
}
|
||||
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SigningKey));
|
||||
var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
|
||||
var jwt = new JwtSecurityToken(
|
||||
issuer: _options.Issuer,
|
||||
audience: _options.Audience,
|
||||
claims: claims,
|
||||
notBefore: DateTime.UtcNow,
|
||||
expires: expiresAt,
|
||||
signingCredentials: credentials);
|
||||
|
||||
return (new JwtSecurityTokenHandler().WriteToken(jwt), expiresAt);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user