2026-02-14 16:50:02 +08:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
"""
|
2026-02-25 19:10:13 +08:00
|
|
|
|
DRF 自定义认证后端:只要请求头包含 Authorization 即视为已认证。
|
2026-02-14 16:50:02 +08:00
|
|
|
|
"""
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-02-25 19:10:13 +08:00
|
|
|
|
class HeaderAuthorizationAuthentication(BaseAuthentication):
|
|
|
|
|
|
"""仅要求请求头中存在 Authorization 字段。"""
|
2026-02-14 16:50:02 +08:00
|
|
|
|
|
|
|
|
|
|
def authenticate(self, request):
|
2026-02-25 19:10:13 +08:00
|
|
|
|
if "HTTP_AUTHORIZATION" not in request.META:
|
|
|
|
|
|
return None # 未携带 Authorization,交给权限类处理
|
2026-02-14 16:50:02 +08:00
|
|
|
|
|
2026-02-25 19:10:13 +08:00
|
|
|
|
# 只要求字段存在,不校验值内容。
|
|
|
|
|
|
auth_value = request.headers.get("Authorization", "")
|
|
|
|
|
|
return (TokenUser("authorization_header_user"), auth_value)
|
2026-02-14 16:50:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-02-25 19:10:13 +08:00
|
|
|
|
# 兼容旧配置名
|
|
|
|
|
|
CookieTokenAuthentication = HeaderAuthorizationAuthentication
|