2
votes

I'm using Django REST along with Djoser as my authentication service. However, when making a post request to the djoser auth endpoints, e.g. .../auth/token/login, the only response I get back is auth_token: xxxxx

E.g, if I make a successful post request such as:

{
  "username": "[email protected]",
  "password": "test12345"
}

My response will be

"auth_token": "XXXXXXXX"

But I'd like to retrieve more than just a token, e.g.

"auth_token": "XXXXXXXX",
"user_id": 8

Any idea on how to make this happen?

1
The question is a bit unclear, what problem are you trying to solve? Since you send the username and password to get the token, do you really need/want to get them back in the response?gregory
Basically, when I'm making a post request to .../auth/token/login with a username and password - if that password and username are valid, I get back a response in the form of "auth_token": "xxxxx". I'd like to get back something like "auth_token": "xxxx", "user_id": 8erikvm
You need to customize the class Djoser uses. A good example doing what you want is already in the Django documentation: django-rest-framework.org/api-guide/authentication/…, see the CustomAuthToken(ObtainAuthToken) class example.gregory

1 Answers

0
votes

Create your own custom token obtain view as below,

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token


class TokenObtainView(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        custom_response = {
            'token': token.key,
            'user_id': user.id
        }
        return Response(custom_response)

and then wire-up your TokenObtainView class in your urls.py

urlpatterns = [
    # other patterns
    path('path/to/your/custom/token/view/', views.TokenObtainView.as_view(), name='new-token,obtain-view')
]

Now onwards, you should use the endpoint, path/to/your/custom/token/view/ to get your customized response.