mirror of
https://github.com/DrizzleTime/Foxel.git
synced 2026-06-02 14:10:25 +08:00
feat(auth): implement cookie-based token management and update user ID retrieval
This commit is contained in:
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user