Logout Django Rest Framework JWT

yierstem picture yierstem · Sep 20, 2018 · Viewed 8.8k times · Source

I want to ask if it's a good idea to logout when I'm using JWT. To log in, I send a post request with username and password to get the desired token (saved into localStorage) which will allow me to send further requests to views that requires the token, of course.

But I'm not sure how should I log out the user. I can clear the localStorage, but the token remains available.

So, I want to ask if I should use refresh the token since I can not disable it.

Answer

a_k_v picture a_k_v · Sep 21, 2018

You are right, even after you remove the JWT token it remains valid token for a period of time until it expires. JWT is stateless. So if you want to handle logout and to invalidate token you must need to keep a database or in memory cache to store the invalid(blacklisted) token. Then you need to add a new permission to check whether the token is blacklisted or not.

class BlackListedToken(models.Model):
    token = models.CharField(max_length=500)
    user = models.ForeignKey(User, related_name="token_user", on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ("token", "user")


class IsTokenValid(BasePermission):
    def has_permission(self, request, view):
        user_id = request.user.id            
        is_allowed_user = True
        token = request.auth.decode("utf-8")
        try:
            is_blackListed = BlackListedToken.objects.get(user=user_id, token=token)
            if is_blackListed:
                is_allowed_user = False
        except BlackListedToken.DoesNotExist:
            is_allowed_user = True
        return is_allowed_user

You can remove the token from the blacklisted list after its expiry.