# -*- coding: utf-8 -*- """ DRF 自定义认证后端:只要请求头包含 Authorization 即视为已认证。 """ from rest_framework.authentication import BaseAuthentication class TokenUser: """轻量用户对象(不依赖 Django auth 模块)。""" def __init__(self, username: str): self.username = username self.is_authenticated = True def __str__(self): return self.username class HeaderAuthorizationAuthentication(BaseAuthentication): """仅要求请求头中存在 Authorization 字段。""" def authenticate(self, request): if "HTTP_AUTHORIZATION" not in request.META: return None # 未携带 Authorization,交给权限类处理 # 只要求字段存在,不校验值内容。 auth_value = request.headers.get("Authorization", "") return (TokenUser("authorization_header_user"), auth_value) # 兼容旧配置名 CookieTokenAuthentication = HeaderAuthorizationAuthentication