使用 Django REST Framework 进行 JWT 身份验证
JWT Authentication with Django REST Framework
我在验证对 Django REST 端点的请求时遇到一些问题。我有一个 token-auth URL 指向 rest_framework_jwt.views.obtain_jwt_token,例如:
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/ returns 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
您应该在请求中提供 jwt 令牌。这是示例:
curl -X POST -H "Content-Type: application/json" -H "Authorization: jwt <MY_TOKEN>" http://localhost/current_user/
您在数据部分错误地发送了令牌,您应该在授权中提供它 header。
我在验证对 Django REST 端点的请求时遇到一些问题。我有一个 token-auth URL 指向 rest_framework_jwt.views.obtain_jwt_token,例如:
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/ returns 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
您应该在请求中提供 jwt 令牌。这是示例:
curl -X POST -H "Content-Type: application/json" -H "Authorization: jwt <MY_TOKEN>" http://localhost/current_user/
您在数据部分错误地发送了令牌,您应该在授权中提供它 header。