From ab642d65aad7b2b933231125d412f4d3a0ec3010 Mon Sep 17 00:00:00 2001 From: "Fraire, Santiago" Date: Fri, 5 Jan 2018 13:57:52 +0100 Subject: [PATCH] docs(authentication): example reimplementing ObtainAuthToken --- docs/api-guide/authentication.md | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 63a789dfc..61176a3a9 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -205,7 +205,35 @@ 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 overriding the `ObtainAuthToken` view class, and using that in your url conf instead. + +Example: + + from rest_framework.authtoken.views import ObtainAuthToken + from rest_framework.authtoken.models import Token + from rest_framework.response import Response + + class CustomAuthToken(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) + return Response({ + 'token': token.key, + 'user_id': user.pk, + 'email': user.email + }) + +And in your `urls.py`: + + urlpatterns += [ + url(r'^api-token-auth/', CustomAuthToken.as_view()) + ] 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.