0

私はdjangorestframework == 3.12.2でDjango 3.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