如何配置我的 Django REST 框架视图以识别我的 "Authorization" header?
How do I configure my Django REST framework view to recognize my "Authorization" header?
我正在使用 Django 3.2 和 djangorestframework==3.12.2。 DRF 似乎不是 recognizing/parsing 我随请求一起发送的授权 header。我在我的设置文件中设置了这个
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
)
}
JWT_AUTH = {
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_GET_USER_SECRET_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_ISSUER': None,
}
并且在相关视图中,我像这样设置我的权限和身份验证类
class UserProfileView(RetrieveAPIView):
permission_classes = (IsAuthenticated,)
authentication_class = JSONWebTokenAuthentication
def get(self, request):
try:
token = get_authorization_header(request).decode('utf-8')
if token is None or token == "null" or token.strip() == "":
raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
decoded = jwt.decode(token, SECRET_KEY)
username = decoded['username']
user = User.objects.get(username=username)
status_code = status.HTTP_200_OK
response = {
'success': 'true',
'status code': status_code,
'message': 'User profile fetched successfully',
'data': {
'email': user.email
}
}
except Exception as e:
status_code = status.HTTP_400_BAD_REQUEST
response = {
'success': 'false',
'status code': status.HTTP_400_BAD_REQUEST,
'message': 'User does not exists',
'error': str(e)
}
return Response(response, status=status_code)
在我的 urls.py 文件中配置它
urlpatterns = [
...
path(r'profile/', views.UserProfileView.as_view()),
]
然而,当我重新启动服务器并尝试访问端点时
curl --header "Content-type: application/json" --header "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImRhdmUiLCJleHAiOjE2MzM5ODMwMTUsImVtYWlsIjoiZGF2ZUBleGFtcGxlLmNvbSJ9.un6qNSdOQ-ExJxAQAIJIqwxyHeidx_2pXP8f1_mqLZY" "http://localhost:8000/profile/"
我收到错误
{"detail":"Authentication credentials were not provided."}
如何配置端点以读取提交的令牌?
在您的 header
中的令牌之前添加 JWT
"Authorization: JWT <your_token>"
我正在使用 Django 3.2 和 djangorestframework==3.12.2。 DRF 似乎不是 recognizing/parsing 我随请求一起发送的授权 header。我在我的设置文件中设置了这个
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
)
}
JWT_AUTH = {
'JWT_SECRET_KEY': SECRET_KEY,
'JWT_GET_USER_SECRET_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_ISSUER': None,
}
并且在相关视图中,我像这样设置我的权限和身份验证类
class UserProfileView(RetrieveAPIView):
permission_classes = (IsAuthenticated,)
authentication_class = JSONWebTokenAuthentication
def get(self, request):
try:
token = get_authorization_header(request).decode('utf-8')
if token is None or token == "null" or token.strip() == "":
raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
decoded = jwt.decode(token, SECRET_KEY)
username = decoded['username']
user = User.objects.get(username=username)
status_code = status.HTTP_200_OK
response = {
'success': 'true',
'status code': status_code,
'message': 'User profile fetched successfully',
'data': {
'email': user.email
}
}
except Exception as e:
status_code = status.HTTP_400_BAD_REQUEST
response = {
'success': 'false',
'status code': status.HTTP_400_BAD_REQUEST,
'message': 'User does not exists',
'error': str(e)
}
return Response(response, status=status_code)
在我的 urls.py 文件中配置它
urlpatterns = [
...
path(r'profile/', views.UserProfileView.as_view()),
]
然而,当我重新启动服务器并尝试访问端点时
curl --header "Content-type: application/json" --header "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImRhdmUiLCJleHAiOjE2MzM5ODMwMTUsImVtYWlsIjoiZGF2ZUBleGFtcGxlLmNvbSJ9.un6qNSdOQ-ExJxAQAIJIqwxyHeidx_2pXP8f1_mqLZY" "http://localhost:8000/profile/"
我收到错误
{"detail":"Authentication credentials were not provided."}
如何配置端点以读取提交的令牌?
在您的 header
中的令牌之前添加 JWT "Authorization: JWT <your_token>"