feat(auth): implement cookie-based token management and update user ID retrieval

This commit is contained in:
ShiYu
2025-06-09 23:57:16 +08:00
parent f7048c3025
commit dbe306d2df
5 changed files with 77 additions and 3 deletions

View File

@@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Mvc;
using Foxel.Models;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Foxel.Controllers
{
@@ -14,6 +17,37 @@ namespace Foxel.Controllers
return userIdClaim != null ? int.Parse(userIdClaim) : null;
}
protected int? GetUserIdFromCookie()
{
try
{
var token = Request.Cookies["token"];
if (string.IsNullOrEmpty(token))
{
return null;
}
var tokenHandler = new JwtSecurityTokenHandler();
if (!tokenHandler.CanReadToken(token))
{
return null;
}
var jwtToken = tokenHandler.ReadJwtToken(token);
var userIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim != null && int.TryParse(userIdClaim, out var userId))
{
return userId;
}
}
catch (Exception)
{
return null;
}
return null;
}
protected ActionResult<BaseResult<T>> Success<T>(T data, string message = "操作成功", int statusCode = 200)
{
return Ok(new BaseResult<T>