This commit is contained in:
SunCheng
2026-02-10 17:49:19 +08:00
parent 3e18283e52
commit d052ae5197
104 changed files with 10369 additions and 3000 deletions

View File

@@ -1,77 +1,23 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Application;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Service.AppSettingModel;
namespace WebApi.Controllers;
[ApiController]
[Route("api/[controller]/[action]")]
public class AuthController : ControllerBase
public class AuthController(
IAuthApplication authApplication,
ILogger<AuthController> logger) : ControllerBase
{
private readonly AuthSettings _authSettings;
private readonly JwtSettings _jwtSettings;
private readonly ILogger<AuthController> _logger;
public AuthController(
IOptions<AuthSettings> authSettings,
IOptions<JwtSettings> jwtSettings,
ILogger<AuthController> logger)
{
_authSettings = authSettings.Value;
_jwtSettings = jwtSettings.Value;
_logger = logger;
}
/// <summary>
/// 用户登录
/// </summary>
[AllowAnonymous]
[HttpPost]
public BaseResponse<LoginResponse> Login([FromBody] LoginRequest request)
public BaseResponse<Application.Dto.LoginResponse> Login([FromBody] Application.Dto.LoginRequest request)
{
// 验证密码
if (string.IsNullOrEmpty(request.Password) || request.Password != _authSettings.Password)
{
_logger.LogWarning("登录失败: 密码错误");
return "密码错误".Fail<LoginResponse>();
}
// 生成JWT Token
var token = GenerateJwtToken();
var expiresAt = DateTime.UtcNow.AddHours(_jwtSettings.ExpirationHours);
_logger.LogInformation("用户登录成功");
return new LoginResponse
{
Token = token,
ExpiresAt = expiresAt
}.Ok();
}
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);
var response = authApplication.Login(request);
logger.LogInformation("用户登录成功");
return response.Ok();
}
}