Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: easier to extend the payload returning the token without having… #5726

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion docs/api-guide/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,17 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a

{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }

Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by inheriting from `ObtainAuthToken` and overriding the `get_data` function, and using that in your url conf instead.

Example:

```
class CustomAuthToken(ObtainAuthToken):

def get_data(self, user, token, created):
return {'token': token.key, 'user_id': user.pk}

```

By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
and include them using the `throttle_classes` attribute.
Expand Down
6 changes: 5 additions & 1 deletion rest_framework/authtoken/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ class ObtainAuthToken(APIView):
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer

def get_data(self, user, token, created):
return {'token': token.key}

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)
return Response({'token': token.key})
data = self.get_data(user, token, created)
return Response(data)


obtain_auth_token = ObtainAuthToken.as_view()