where should i add the django rest framework token in http. header or body?

99 Views Asked by At

Im a new in django rest framework. im developing a user registration, login and logout page for first. in many of the tutorial i found that, they add the token in the body. but in the drf documentation , they it shoud be in the body. im so confuced. anyone help me with the logic

i just created a login page. the view is testing the username and the password then return user information and the token. but how do i return the token. here is my login view. can u review my code:

# user login
class user_login(APIView):
    serializer_class = login_serializer

    def post(self, request, format = None):
        print(request.data)
        """
        serialing the data and validating it, any exception found is_valied()
        the functionn automatically return respond with the error message as a dictionery
        """

        # serializing data
        serializer = self.serializer_class(data=request.data)

        # validating the data
        serializer.is_valid(raise_exception=True)

        # authenticate the user
        email = serializer.validated_data['email']
        password = serializer.validated_data['password']
        user = authenticate(request, email = email, password = password)
        
        # if user is authenticated create tocken
        if user:
            token, created = Token.objects.get_or_create(user = user)
            print(request.user)
            print(request.auth)
            return Response({"status":200, "email": email, "token": token.key}, status=200)

        # else return 401 unautherized message
        else:
            return Response({"status":401,"message":"unauthorized"}, status=401)   ```


1

There are 1 best solutions below

3
FreeCreativ On

Browsers don't expose that to clients for security purposes but you can use a tool like Postman or it's alternatives to do that. after sending the login post request and you get your token key, copy it and paste in the authorization header and enter "token" first space the paste the token. NB enter token without the double quotes