fix
This commit is contained in:
85
Application/AuthApplication.cs
Normal file
85
Application/AuthApplication.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Service.AppSettingModel;
|
||||
|
||||
namespace Application;
|
||||
|
||||
/// <summary>
|
||||
/// 认证应用服务接口
|
||||
/// </summary>
|
||||
public interface IAuthApplication
|
||||
{
|
||||
/// <summary>
|
||||
/// 用户登录
|
||||
/// </summary>
|
||||
LoginResponse Login(LoginRequest request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 认证应用服务实现
|
||||
/// </summary>
|
||||
public class AuthApplication(
|
||||
IOptions<AuthSettings> authSettings,
|
||||
IOptions<JwtSettings> jwtSettings,
|
||||
ILogger<AuthApplication> logger) : IAuthApplication
|
||||
{
|
||||
private readonly AuthSettings _authSettings = authSettings.Value;
|
||||
private readonly JwtSettings _jwtSettings = jwtSettings.Value;
|
||||
private readonly ILogger<AuthApplication> _logger = logger;
|
||||
|
||||
public LoginResponse Login(LoginRequest request)
|
||||
{
|
||||
// 验证密码
|
||||
if (string.IsNullOrEmpty(request.Password))
|
||||
{
|
||||
throw new ValidationException("密码不能为空");
|
||||
}
|
||||
|
||||
if (request.Password != _authSettings.Password)
|
||||
{
|
||||
_logger.LogWarning("登录失败: 密码错误");
|
||||
throw new ValidationException("密码错误");
|
||||
}
|
||||
|
||||
// 生成JWT Token
|
||||
var token = GenerateJwtToken();
|
||||
var expiresAt = DateTime.UtcNow.AddHours(_jwtSettings.ExpirationHours);
|
||||
|
||||
_logger.LogInformation("用户登录成功");
|
||||
|
||||
return new LoginResponse
|
||||
{
|
||||
Token = token,
|
||||
ExpiresAt = expiresAt
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成JWT Token
|
||||
/// </summary>
|
||||
private string GenerateJwtToken()
|
||||
{
|
||||
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
|
||||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||
new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()),
|
||||
new Claim("auth", "password-auth")
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _jwtSettings.Issuer,
|
||||
audience: _jwtSettings.Audience,
|
||||
claims: claims,
|
||||
expires: DateTime.UtcNow.AddHours(_jwtSettings.ExpirationHours),
|
||||
signingCredentials: credentials
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user