Reputation: 982
I am using rest_framework_simplejwt authentication in my DRF backend. Everything works absolutely fine when I am using the DRF browser in terms of authentication and having access to predefined API endpoints.
However, when I want to programmatically access the endpoints for the post/patch method I get Authentication credentials were not provided. error. Here is my settings:
ALLOWED_HOSTS = ['*']
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'propertypost.apps.PropertyConfig',
'users.apps.UsersConfig',
'rest_framework',
# 3rd party
'django_filters',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'allauth.socialaccount',
'django.contrib.gis',
]
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10,
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter',
'rest_framework.filters.SearchFilter',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated',
),
}
...
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=525600),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=120),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
AUTH_USER_MODEL = 'users.CustomUser'
REST_USE_JWT = True
as I said, above setting works perfectly in DRF browser, but when here when I try to request a patch method it gives Authentication credentials were not provided:
AUTH_ENDPOINT = "http://127.0.0.1:8000/rest-auth/login"
data = {
'username': username,
'password': password
headers = {
"Content-Type": "application/json"
}
r = requests.post(AUTH_ENDPOINT, data=json.dumps(data), headers=headers)
token=r.json()['token']
data = {
'age': 8,
}
headers = {
"Content-Type": "application/json",
"Authorization": "JWT " + token,
}
r = requests.patch(POST_ENDPOINT, data=json.dumps(data), headers=headers)
Upvotes: 1
Views: 1061
Reputation: 88429
From the Usage section, the headers must be in the following format
"Authorization: Bearer YourToken"
So, Change your headers to,
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + token,
}
Upvotes: 2