0

我正在使用 Django 3.2 和 djangorestframework==3.12.2。DRF 似乎没有识别/解析我随请求发送的授权标头。我在我的设置文件中设置了这个

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."}

如何配置端点以读取提交的令牌?

4

1 回答 1

0

在标头中的令牌之前添加 JWT

 "Authorization: JWT <your_token>"

参考这个文档:https ://jpadilla.github.io/django-rest-framework-jwt/

于 2021-10-11T19:24:13.453 回答