fix: JWT认证兼容旧版user_id claim,解决客服后台401

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
XingQue
2026-07-01 11:36:12 +08:00
parent 47c6e3b024
commit 243ab5b817
2 changed files with 40 additions and 1 deletions

View File

@@ -165,7 +165,7 @@ AUTH_USER_MODEL = 'yonghu.UserMain'
# DRF配置也非常简单
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'utils.jwt_auth.YonghuidJWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',

39
utils/jwt_auth.py Normal file
View File

@@ -0,0 +1,39 @@
"""
自定义 JWT 认证:兼容旧版 tokenclaim 为 user_id与新版claim 为 yonghuid
"""
from django.utils.translation import gettext_lazy as _
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import AuthenticationFailed, InvalidToken
from rest_framework_simplejwt.settings import api_settings
class YonghuidJWTAuthentication(JWTAuthentication):
"""签发与校验均以 yonghuid 为准,同时兼容历史 user_id claim。"""
def get_user(self, validated_token):
user_id, lookup_field = self._resolve_user_identity(validated_token)
if user_id is None:
raise InvalidToken(_('Token contained no recognizable user identification'))
try:
return self.user_model.objects.get(**{lookup_field: user_id})
except self.user_model.DoesNotExist as exc:
raise AuthenticationFailed(_('User not found'), code='user_not_found') from exc
def _resolve_user_identity(self, validated_token):
claim = api_settings.USER_ID_CLAIM
field = api_settings.USER_ID_FIELD
if claim in validated_token:
return str(validated_token[claim]), field
legacy_id = validated_token.get('user_id')
if legacy_id is None:
return None, field
legacy_id = str(legacy_id)
# 旧 token 可能写入主键 id需回退按 id 查询
if field != 'id' and legacy_id.isdigit():
if self.user_model.objects.filter(id=int(legacy_id)).exists():
return legacy_id, 'id'
return legacy_id, field