2

我在验证对 Django REST 端点的请求时遇到了一些问题。我有一个指向 rest_framework_jwt.views.obtain_jwt_token 的 token-auth URL,例如:

urlpatterns = [
    path('token-auth/', obtain_jwt_token),
    path('verify-token/', verify_jwt_token),
    path('current_user/', CurrentUserView.as_view()),
]

CurrentUserView 是:

class CurrentUserView(APIView):
    def post(self, request):
        print(request.user)
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

如果我通过访问http://localhost/token-auth/在浏览器中创建令牌,则可以使用以下命令对其进行验证:

curl -X POST -H "Content-Type: application/json" -d '{"token":<MY_TOKEN>}' http://localhost/verify-token/

但是调用http://localhost/current_user/的相同请求返回 400 代码:

curl -X POST -H "Content-Type: application/json" -d '{"token":<MY_TOKEN>}' http://localhost/current_user/

{"detail":"Authentication credentials were not provided."}

框架设置为:

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

Django 正在使用以下 Dockerfile 的容器中运行:

FROM python:3
WORKDIR /code
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
ENV PYTHONUNBUFFERED=1
EXPOSE 8000
4

1 回答 1

1

您应该在请求中提供 jwt 令牌。这是示例:

curl -X POST -H "Content-Type: application/json" -H "Authorization: jwt <MY_TOKEN>" http://localhost/current_user/

您在数据部分错误地发送了令牌,而应该在授权标头中提供它。

于 2018-11-30T20:04:34.713 回答