首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改rest_framework的TokenAuthorization的头键

更改rest_framework的TokenAuthorization的头键
EN

Stack Overflow用户
提问于 2022-04-20 00:17:45
回答 1查看 130关注 0票数 1

默认情况下,rest_ for的TokenAuthentication在标题中使用“授权”键,并在验证请求时查找关键字"Token“。

代码语言:javascript
复制
Authorization: Token [value]

如何将其更改为使用“AUTH”键而不使用关键字?

代码语言:javascript
复制
API-AUTH: [value]
EN

回答 1

Stack Overflow用户

发布于 2022-04-24 10:57:46

您必须创建一个从TokenAuthentication扩展并重写.authenticate()方法的自定义权限类。

下面的代码是TokenAuthentication.authenticate()的修改代码,该代码接受以API-AUTH作为auth头名的请求,该请求的值为no关键字。您可以在GitHub of Django rest框架这里中找到原始源代码。

代码语言:javascript
复制
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添加到设置中。

代码语言:javascript
复制
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...  # other permission classes
        'path.to.CustomTokenAuthentication',
    ),
    ...  # other settings
}

Notes

  • 有关自定义身份验证的更多信息可以找到这里
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71932727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档