Reputation: 450
I'm new to django_rest_framework and trying to implement JWT authentication . But there is a problem however I send the token that created by username and password that has been sent but this error fires out.
{"detail":"Authentication credentials were not provided."}
Generating Token:
TOKEN_ENDPOINT = 'http://127.0.0.1:8000/api/auth/token/'
user_data = {
'username': 'admin',
'password': 1234
}
json_user_data = json.dumps(user_data)
user_headers = {
'content-type': 'application/json'
}
token_response = requests.request('post', TOKEN_ENDPOINT, data=json_user_data, headers=user_headers)
token = token_response.json()['token']
Sending new post request with generated token:
headers = {
'Content-Type': 'application/json',
"Authorization": "JWT" + token,
}
data = json.dumps({"content": "Hellllllllloooo"})
new_content_req = requests.post(ENDPOINT, data=data,
headers=headers)
print(new_content_req.text) // {"detail":"Authentication credentials were not provided."}
REST_FRAMEWORK Default authentication and permissions:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
}
Prefix:
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_AUTH_COOKIE': None,
View:
class StatusAPIView(mixins.CreateModelMixin, generics.ListAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
# authentication_classes = [SessionAuthentication]
queryset = Status.objects.all()
serializer_class = StatusSerializer
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
Upvotes: 0
Views: 900
Reputation: 837
Add a space after JWT
headers = {
'Content-Type': 'application/json',
"Authorization": "JWT " + token,
}
data = json.dumps({"content": "Hellllllllloooo"})
new_content_req = requests.post(ENDPOINT, data=data,
headers=headers)
print(new_content_req.text)
Upvotes: 2