【问题标题】:JWT Authentication with Django REST Framework使用 Django REST 框架进行 JWT 身份验证
【发布时间】:2019-05-02 22:51:38
【问题描述】:

我在验证对 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

【问题讨论】:

    标签: django rest django-rest-framework jwt django-rest-framework-jwt


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢@Reza。你是对的,verify_jwt_token 视图需要将令牌作为数据发送,因为我猜它不是一种身份验证方法,而只是一个表单响应
    • 任何时候我的朋友 :)
    猜你喜欢
    • 2018-12-15
    • 2019-03-01
    • 2021-12-21
    • 2019-07-11
    • 2017-12-05
    • 2021-08-06
    • 2018-10-17
    • 1970-01-01
    • 2013-06-29
    相关资源
    最近更新 更多