I'm using Django 3.2 with djangorestframework==3.12.2. DRF doesn't seem to be recognizing/parsing the authorization header I'm sending with my requests. I have this set up in my settings file
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,
}
and in the relevant view, I set up my perms and auth classes like so
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)
configurign this in my urls.py file
urlpatterns = [
...
path(r'profile/', views.UserProfileView.as_view()),
]
However when I restart my server and try and hit the endpoint
curl --header "Content-type: application/json" --header "Authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImRhdmUiLCJleHAiOjE2MzM5ODMwMTUsImVtYWlsIjoiZGF2ZUBleGFtcGxlLmNvbSJ9.un6qNSdOQ-ExJxAQAIJIqwxyHeidx_2pXP8f1_mqLZY" "http://localhost:8000/profile/"
I get the error
{"detail":"Authentication credentials were not provided."}
How do I configure the endpoint to read the token submitted?
add JWT before the token in your header
"Authorization: JWT <your_token>"
refer this docs: https://jpadilla.github.io/django-rest-framework-jwt/