2

I am using django rest framework Token Authentication. In case if I call a url, providing a token (Token aesdghfhkjdsajgaadsa) which is invalid or already deleted, I get a pop up asking for username and password. How can I avoid that pop up? I just need a response as

{"status": -1, "errors": "Token Expired"}

I am using a custom token authentication as given,

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 < utc_now - timedelta(hours=24):
        token.delete()
        raise exceptions.AuthenticationFailed('Token has expired')

    return token.user, token

Is there a solution for this?

Arundas R
  • 770
  • 7
  • 20

2 Answers2

2

I assume the pop-up is a username/password generated by the HTTP Basic/Digest authentication schemes? That's most likely coming from the BasicAuthentication authentication class.

Django Rest Framework will iterate through the authentication methods listed in DEFAULT_AUTHENTICATION_CLASSES unless you have explicitly provided a list in the APIView.authentication_classes.

http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme

Dwight Gunning
  • 2,485
  • 25
  • 39
  • That was correct. I had to change my DEFAULT_AUTHENTICATION_CLASSES list. When i remove BasicAuthentication from my list I got the solution. Thanks – Arundas R Apr 30 '15 at 05:29
-1

I hope you want something like this:

    def authenticate_credentials(self, key):
        resp = {}
        try:
            token = self.model.objects.get(key=key)
        except self.model.DoesNotExist:
            resp["status"] = -1
            resp["errors"] = "Invalid token"
            return resp

        if not token.user.is_active:
            resp["status"] = -1
            resp["errors"] = "User inactive or deleted"
            return resp

        # This is required for the time comparison
        utc_now = datetime.utcnow()
        utc_now = utc_now.replace(tzinfo=pytz.utc)

        if token.created < utc_now - timedelta(hours=24):
            token.delete()
            resp["status"] = -1
            resp["errors"] = "Token has expired"
            return resp

        return token.user, token
Shailesh
  • 367
  • 1
  • 5
  • 15