Reputation: 33
I am using Django REST Framework and following this tutorial for retrieving all users when admin user is authenticated.
Class-based APIView of Django REST Framework
I am using Postman to test and trying to retrieve the list of all users registered in the system.
At first I try to use my "User Login with Token" API in Postman to create the necessary token as shown below:
I copied the value of the "token" key and pasted it as the value of the "Authorization" key in the "Headers" section of "Get All Users" API in Postman as shown below. It is a GET request and I get the error "detail": "Authentication credentials were not provided."
as the response.
Necessary code snippets are as follows:
views.py
class UserAccountListView(APIView):
"""
List of All Users in the System / Application
* Requires Token Authentication.
* Only Admin Users are able to access this view.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAdminUser, )
def get(self, request, format=None):
"""
Returns a List of All Users
"""
full_names = [user.full_name for user in UsersAccount.objects.all()]
return Response(full_names)
settings.py
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.IsAdminUser',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=30),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
"ROTATE_REFRESH_TOKENS": False,
"BLACKLIST_AFTER_ROTATION": False,
"UPDATE_LAST_LOGIN": True,
"ALGORITHM": "HS256",
"SIGNING_KEY": SECRET_KEY,
"VERIFYING_KEY": None,
"AUDIENCE": None,
"ISSUER": None,
"AUTH_HEADER_TYPES": ("Bearer", ),
"AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "user_id",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken", ),
"TOKEN_TYPE_CLAIM": "token_type",
"JTI_CLAIM": "jti",
"SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
"SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
"SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
}
urls.py
urlpatterns = [
path('', UsersAccountAPIOverview.as_view()),
path("all", UserAccountListView.as_view()),
path("register", UsersAccountRegistrationView.as_view()),
path("token", UserAccountTokenObtainPairView.as_view()),
path("token/refresh", TokenRefreshView.as_view()),
path("token/verify", TokenVerifyView.as_view()),
]
Looking forward for your kind support and help. If you need further information, I will provide you.
Thank you.
Upvotes: 1
Views: 13342
Reputation: 652
If you are running Django on Apache using mod_wsgi you have to add
WSGIPassAuthorization On
in your httpd.conf
Upvotes: 1
Reputation: 31
instead of
authentication_classes = (TokenAuthentication, )
use
from rest_framework_simplejwt.authentication import JWTAuthentication
authentication_classes = [JWTAuthentication]
Upvotes: 1
Reputation: 21
I had the same issue with postman, but when I tried it using Python requests and including the token in the header, it worked fine.
import requests
headers = {'Authorization': 'Token 5a96b81e073c1cf052cf385187b1f299677de386f74b566c6cfcd5287aeac8d4'}
res = requests.get('http://localhost:8000/api/test/', headers=headers)
Upvotes: 0
Reputation: 21
I'm using cookiecuter + django and it's awesome as well as a kick on your butt. jaja but since I was interesting on going on with my project I just commented this lines at base.py (in your case it would be at settings.py)
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
# "rest_framework.authentication.SessionAuthentication",
# "rest_framework.authentication.TokenAuthentication",
),
# "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}
and this worked for me just to test my endpoints out, I know it is not the best way but works, I'll update my answer later with a better aproach.
Upvotes: -1
Reputation: 274
In your views.py remove the line:
authentication_classes = (TokenAuthentication, )
This is because in your settings.py file, the first line:
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
...
],
mentions JWTAuthentication and not TokenAuthentication
Upvotes: 3
Reputation: 134
You must add Bearer in postman :
"Authorization" : "Bearer [token]"
Upvotes: 3