Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is good practice to have mobile clients periodically renew their authentication token. This of course is up to the server to enforce.</p> <p>The default TokenAuthentication class does not support this, however you can extend it to achieve this functionality.</p> <p>For example: </p> <pre><code>from rest_framework.authentication import TokenAuthentication, get_authorization_header from rest_framework.exceptions import AuthenticationFailed class ExpiringTokenAuthentication(TokenAuthentication): def authenticate_credentials(self, key): try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') if not token.user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted') # This is required for the time comparison utc_now = datetime.utcnow() utc_now = utc_now.replace(tzinfo=pytz.utc) if token.created &lt; utc_now - timedelta(hours=24): raise exceptions.AuthenticationFailed('Token has expired') return token.user, token </code></pre> <p>It is also required to override the default rest framework login view, so that the token is refreshed whenever a login is done:</p> <pre><code>class ObtainExpiringAuthToken(ObtainAuthToken): def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): token, created = Token.objects.get_or_create(user=serializer.validated_data['user']) if not created: # update the created time of the token to keep it valid token.created = datetime.datetime.utcnow() token.save() return Response({'token': token.key}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) obtain_expiring_auth_token = ObtainExpiringAuthToken.as_view() </code></pre> <p>And don't forget to modify the urls:</p> <pre><code>urlpatterns += patterns( '', url(r'^users/login/?$', '&lt;path_to_file&gt;.obtain_expiring_auth_token'), ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload