Reputation: 137
I am testing django rest framework using python requests module but its says an error. I am just beginner rest-api developer.
DRF setting main.py
import datetime
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.BasicAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
)
}
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': False,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT', # Authorization: JWT <token>
'JWT_AUTH_COOKIE': None,
}
and my testing code is
import os
import json
import requests
AUTH_ENDPOINT = 'http://127.0.0.1:8000/api/auth/jwt/'
ENDPOINT = 'http://127.0.0.1:8000/api/status/'
image_path = os.path.join(os.getcwd(), 'drf.png')
headers = {
"Content-Type": "application/json"
}
data = {
"username": 'jaki',
"password": 'SADHIN101119'
}
r = requests.post(AUTH_ENDPOINT, data=json.dumps(data), headers=headers)
token = r.json()['token']
headers = {
"Content-Type": "application/json",
"Authorization": "JWT" + token
}
post_data = json.dumps({"content": "some random content"})
posted_response = requests.post(ENDPOINT, data=post_data, headers=headers)
print(posted_response.text)
Error showing
{"detail":"Authentication credentials were not provided."}
How can i solve the problem. Thanks.
Upvotes: 0
Views: 1008
Reputation: 23054
In the Authorization
header, the JWT
prefix and token must be separated with a space. Change your Authorization
header to:
"Authorization": "JWT " + token
Upvotes: 1
Reputation: 797
This a a hunch ... but uncomment out
# 'rest_framework.authentication.BasicAuthentication'
When you're trying to get your Token, you're using BasicAuth to send over your login creds. That's probably failing.
Upvotes: 0