from rest_framework_simplejwt.authentication import JWTAuthentication class CookieOrHeaderJWTAuthentication(JWTAuthentication): """ 双模 JWT 认证器: 1. 优先从 HTTP Authorization 头读取 Bearer Token(移动端 Android / iOS / API 客户端); 2. 若 Authorization 头不存在,则从 HttpOnly Cookie 中读取 access_token(Web 端,杜绝 XSS 窃取)。 """ def authenticate(self, request): header = self.get_header(request) if header is not None: raw_token = self.get_raw_token(header) else: # 从 HttpOnly Cookie 读取 access_token raw_token = request.COOKIES.get('access_token') if raw_token: raw_token = raw_token.encode('utf-8') if raw_token is None: return None validated_token = self.get_validated_token(raw_token) return self.get_user(validated_token), validated_token