Logout Django Rest Framework JWT

yierstem 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.

Thanks in advance

djangodjango-rest-frameworkjwtsession-statedjango-rest-framework-jwt

Answers

answered 4 weeks ago argo #1

Every JWT which you issue should have an expiry datetime, so whenever you are logging out the user you should delete the jwt-token from the localstorage cookie.

but the token remains available.

Not sure what the above line means but you should not worry about if the token remains available to the user or not after you clear it from localstorage and cookie because either way it would get invalid after the expiry date.

answered 4 weeks ago a_k_v #2

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
        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.

comments powered by Disqus