首页 > 解决方案 > 令牌授权 Django {"detail":"未提供身份验证凭据。"}

问题描述

我正在尝试在我的服务器 API 上实现基于令牌的授权。但是,当我触发查询时,它会返回{"detail": "Authentication credentials were not provided."}

我已经完成了各种帖子以及 Django 文档中推荐的几乎所有设置。

在我的settings.py

INSTALLED_APPS = [
    'rest_framework.authtoken',
]

并且,

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.TokenAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
       'rest_framework.permissions.IsAuthenticated',
   ),
}

在我的视图文件中:

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated


class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

在我在 WSGI 的 Apache Config 文件中

WSGIPassAuthorization On

RewriteEngine on
 RewriteCond %{HTTP:Authorization} ^(.*)
 RewriteRule .* - [e=HTTP-AUTHORIZATION:%1]

我不知道我是否错过了除此之外的任何东西。令牌是使用命令行在超级用户级别预先生成的。

标签: djangodjango-rest-frameworkbearer-token

解决方案


你见过这个相关的 SO 问题吗?

如果您使用的是 mod_wsgi,请忽略 REWRITE 部分,放在,和指令WSGIPassAuthorization On下方。刚刚让我的 Apache + mod_wsgi 配置工作,看起来像这样:WSGIScriptAliasWSGIDaemonProcessWSGIProcessGroup

...

    WSGIScriptAlias / /var/www/html/base/wsgi.py
    WSGIDaemonProcess django_app python-path=/var/www/html python-home=/var/www/html/env
    WSGIProcessGroup django_app
    WSGIPassAuthorization On

...

推荐阅读