默认情况下,rest_ for的TokenAuthentication在标题中使用“授权”键,并在验证请求时查找关键字"Token“。
Authorization: Token [value]如何将其更改为使用“AUTH”键而不使用关键字?
API-AUTH: [value]发布于 2022-04-24 10:57:46
您必须创建一个从TokenAuthentication扩展并重写.authenticate()方法的自定义权限类。
下面的代码是TokenAuthentication.authenticate()的修改代码,该代码接受以API-AUTH作为auth头名的请求,该请求的值为no关键字。您可以在GitHub of Django rest框架这里中找到原始源代码。
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework import HTTP_HEADER_ENCODING
class CustomTokenAuthentication(authentication.TokenAuthentication):
def authenticate(self, request):
auth = request.META.get('HTTP_API_AUTH', b'')
if isinstance(auth, str):
# Work around django test client oddness
auth = auth.encode(HTTP_HEADER_ENCODING)
auth = auth.split()
if not auth:
return None
elif len(auth) > 1:
msg = _('Invalid token header. Token string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[0].decode()
except UnicodeError:
msg = _('Invalid token header. Token string should not contain invalid characters.')
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_credentials(token)然后可以将CustomTokenAuthentication添加到设置中。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
... # other permission classes
'path.to.CustomTokenAuthentication',
),
... # other settings
}Notes
https://stackoverflow.com/questions/71932727
复制相似问题