Files
boss_dp/server/core/authentication.py
ddrwode 42b68ededd ha'ha
2026-02-25 19:10:13 +08:00

33 lines
990 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- 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