Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.
settings.py
INSTALLED_APPS = [
.
.
'<your_app_name>',
'rest_framework',
'corsheaders',
'rest_framework.authtoken' #new
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
views.py
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response import Response
from django.contrib.auth.hashers import check_password
@api_view(['GET'])
def getData(request):
users = User.objects.all()
users_serializer = MyUserSerializer(users, many=True)
return Response(users_serializer.data)
class TokenAuthentication(APIView):
def post(self, request, format=None):
data = request.data
if('username' in data):
try:
user = User.objects.get(username=data['username'])
checkPassword = check_password(data['password'], user.password)
if(checkPassword):
#If token is not created, the following will create a new token for the user instance.
token,created = Token.objects.get_or_create(user=user)
token_data = {
"user_id": user.id,
"token": token.key
}
return Response(token_data)
else:
return Response("Password is incorrect.")
except ObjectDoesNotExist:
return Response("Invalid user details")
else:
return Response("Please fill the form.")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.getData),
path('token_auth/', views.TokenAuthentication.as_view())
]
serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
class MyUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
Top comments (0)