Django REST Framework 身份验证关键字

Django REST Framework Authentication keyword

我正在尝试按照文档中的建议将 Rest_framework TokenAuthentication 关键字从 "Token" 重命名为 "Bearer" 我已经对 TokenAuthentication [=29] 进行了子class =] 像这样:

在模块中:user/authentication.py

from rest_framework import authentication

class TokenAuthentication(authentication.TokenAuthentication):
    """
    Simple token based authentication.
    Clients should authenticate by passing the token key in the "Authorization"
    HTTP header, prepended with the string "Token ".  For example:
    Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
    """

    keyword = 'Bearer'

在模块 app/settings.py

 REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'user.authentication.TokenAuthentication',
     ),
 }

当我使用 'Authorization: Bearer ...token...' 但不使用 'Authorization: Token ...token...'

时,它仍然向我发送 401 Unauthorized

我做错了什么?

您错过了最后一步。在 View class 中导入包含新关键字的 TokenAuthentication class,而不是默认的 TokenAuthentication class。

从rest_framework导入认证

class TokenAuthentication(authentication.TokenAuthentication):

authentication.TokenAuthentication.keyword = 'Bearer'