😎优化用户令牌版本号缓存逻辑(服务重启后缓存重建)

This commit is contained in:
zuohuaijun 2025-04-06 01:55:21 +08:00
parent ae4798cd9b
commit de9bde949d
2 changed files with 17 additions and 10 deletions

View File

@ -12,6 +12,7 @@ using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
@ -42,8 +43,16 @@ namespace Admin.NET.Web.Core
// 验证Token版本号
var userId = context.User.FindFirst(ClaimConst.UserId)?.Value;
var tokenVersion = context.User.FindFirst(ClaimConst.TokenVersion)?.Value;
if (sysCacheService.Get<string>($"{CacheConst.KeyUserToken}{userId}") != tokenVersion)
var tokenVersion1 = context.User.FindFirst(ClaimConst.TokenVersion)?.Value;
var tokenVersion2 = sysCacheService.Get<string>($"{CacheConst.KeyUserToken}{userId}");
if (string.IsNullOrWhiteSpace(tokenVersion2))
{
// 查库并缓存用户Token版本
var user = await serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>().Queryable<SysUser>().FirstAsync(u => u.Id == long.Parse(userId));
sysCacheService.Set($"{CacheConst.KeyUserToken}{user.Id}", $"{user.TokenVersion}");
tokenVersion2 = user.TokenVersion.ToString();
}
if (tokenVersion1 != tokenVersion2)
{
context.Fail(new AuthorizationFailureReason(this, "令牌已失效,请重新登录。"));
context.GetCurrentHttpContext().SignoutToSwagger();
@ -72,13 +81,11 @@ namespace Admin.NET.Web.Core
}
else
{
context.Fail(); // 授权失败
// 授权失败
context.Fail();
var currentHttpContext = context.GetCurrentHttpContext();
if (currentHttpContext == null)
return;
// 跳过由于 SignatureAuthentication 引发的失败
if (currentHttpContext.Items.ContainsKey(SignatureAuthenticationDefaults.AuthenticateFailMsgKey))
return;
// 跳过签名 SignatureAuthentication 引发的失败
if (currentHttpContext.Items.ContainsKey(SignatureAuthenticationDefaults.AuthenticateFailMsgKey)) return;
currentHttpContext.SignoutToSwagger();
}
}

View File

@ -70,7 +70,7 @@
"vue-demi": "0.14.10",
"vue-draggable-plus": "^0.6.0",
"vue-grid-layout": "3.0.0-beta1",
"vue-i18n": "^11.1.2",
"vue-i18n": "^11.1.3",
"vue-json-pretty": "^2.4.0",
"vue-plugin-hiprint": "^0.0.60",
"vue-router": "^4.5.0",
@ -100,7 +100,7 @@
"eslint": "^9.24.0",
"eslint-plugin-vue": "^10.0.0",
"globals": "^16.0.0",
"less": "^4.2.2",
"less": "^4.3.0",
"openapi-ts-request": "^1.3.0",
"prettier": "^3.5.3",
"rollup-plugin-visualizer": "^5.14.0",