I am working with Token Authentication using Django REST Framework. I am generating a new token during User Registration. I need to pass this token to the frontend including in header. These are my code:
settings.py:
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
...
]
urls.py: (project level)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('accounts.urls')),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
urls.py: (app level)
urlpatterns = [
path('signup/', views.Register.as_view({"post":"register"}), name='users'),
path('login/', views.Login.as_view({"post":"create"}), name='login'),
path('profile/', views.Profile.as_view({"get":"list"}), name='profile'),
]
views.py:
# Register View
class Register(viewsets.GenericViewSet, mixins.CreateModelMixin,):
serializer_class = UserRegisterSerializer
def register(self, request):
data_dict = self.request.data
firstname = data_dict['firstname']
lastname = data_dict['lastname']
username = data_dict['username']
email = data_dict['email']
password = data_dict['password']
mobile = data_dict['mobile']
data = userRegistrationModel.objects.create(firstname=firstname, lastname=lastname, username=username, email=email, password=password, mobile=mobile)
if data:
user = data.set_password(password)
data.save()
token = Token.objects.create(user=data)
return Response({"message": "Registered Successfully", "code": "HTTP_201_CREATED", "Token": token.key})
else:
return Response({"message": "Sorry Try Next Time!!!", "code": "HTTP_403_FORBIDDEN"})
# Login View
class Login(viewsets.GenericViewSet, mixins.CreateModelMixin,):
permission_classes = (AllowAny,)
serializer_class = UserLoginSerializer
def create(self, request, *args, **kwargs):
data_dict = self.request.data
email = data_dict['email']
password = data_dict['password']
data = authenticate(email=email, password=password)
if data:
users = Token.objects.filter(user=data).first()
userData = UserRegisterSerializer(data)
return Response({"message": "Login Successfully", "code": "HTTP_200_OK", "token": users.key, "user": userData.data})
else:
return Response({"message": "Invalid Login", "code": "HTTP_401_UNAUTHORIZED"})
# Profile View
class Profile(viewsets.ViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = UserProfileSerializer
def list(self, request, pk):
queryset = userRegistrationModel.objects.get(id=pk)
serializer_class = UserProfileSerializer
...
...
This is screenshot of generating the Token
Till here (while generating the new Token) it is working perfectly. Now when I am including this Token in LoginView then it is not validating.
Is there any best way to send this Token to the frontend by including in header or if we can update the previous Token by new Token in Login View.
I am not getting that how to work with Django REST Framework default authtoken. Please guide me what is the standard process of using Token Based Authentication.