feat(认证): 添加token滑动过期功能

当TOKEN_SLIDING_EXPIRE启用时,用户操作会自动续期access_token和refresh_token的有效期
This commit is contained in:
zhangtao
2026-02-01 04:09:47 +08:00
parent f368642395
commit c9604f6c2b
2 changed files with 13 additions and 0 deletions
+1
View File
@@ -69,6 +69,7 @@ class Settings(BaseSettings):
REFRESH_TOKEN_EXPIRE_MINUTES: int = 60 * 30 # refresh_token过期时间(秒)30 分钟 REFRESH_TOKEN_EXPIRE_MINUTES: int = 60 * 30 # refresh_token过期时间(秒)30 分钟
TOKEN_TYPE: str = "bearer" # token类型 TOKEN_TYPE: str = "bearer" # token类型
TOKEN_REQUEST_PATH_EXCLUDE: list[str] = ["api/v1/auth/login"] # JWT / RBAC 路由白名单 TOKEN_REQUEST_PATH_EXCLUDE: list[str] = ["api/v1/auth/login"] # JWT / RBAC 路由白名单
TOKEN_SLIDING_EXPIRE: bool = True # 是否启用滑动过期(用户操作时自动续期)
# ================================================= # # ================================================= #
# ******************** 数据库配置 ******************* # # ******************** 数据库配置 ******************* #
+12
View File
@@ -10,6 +10,7 @@ from app.api.v1.module_system.auth.schema import AuthSchema
from app.api.v1.module_system.user.crud import UserCRUD from app.api.v1.module_system.user.crud import UserCRUD
from app.api.v1.module_system.user.model import UserModel from app.api.v1.module_system.user.model import UserModel
from app.common.enums import RedisInitKeyConfig from app.common.enums import RedisInitKeyConfig
from app.config.setting import settings
from app.core.database import async_db_session from app.core.database import async_db_session
from app.core.exceptions import CustomException from app.core.exceptions import CustomException
from app.core.logger import log from app.core.logger import log
@@ -83,6 +84,17 @@ async def get_current_user(
if not online_ok: if not online_ok:
raise CustomException(msg="认证已失效", code=10401, status_code=401) raise CustomException(msg="认证已失效", code=10401, status_code=401)
# 如果启用了滑动过期,自动续期token
if settings.TOKEN_SLIDING_EXPIRE:
await RedisCURD(redis).expire(
key=f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id}",
expire=settings.ACCESS_TOKEN_EXPIRE_MINUTES,
)
await RedisCURD(redis).expire(
key=f"{RedisInitKeyConfig.REFRESH_TOKEN.key}:{session_id}",
expire=settings.REFRESH_TOKEN_EXPIRE_MINUTES,
)
# 关闭数据权限过滤,避免当前用户查询被拦截 # 关闭数据权限过滤,避免当前用户查询被拦截
auth = AuthSchema(db=db, check_data_scope=False) auth = AuthSchema(db=db, check_data_scope=False)
username = user_info.get("user_name") username = user_info.get("user_name")