How to destroy JWT Tokens on logout?

2019-01-21 14:28发布

I am using jwt plugin and strategy in hapijs. I am able to create jwt token while login user and authenticate other API using the same token through 'jwt' strategy. I am setting the token in 'request.state.USER_SESSION' as a cookie where USER_SESSION is token name. Also I am not saving these token in database. But how can I destroy jwt token at the time of logout. Please suggest a way.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-21 14:30

You cannot manually expire a token after it has been created. Thus, you cannot actually log out with JWT on the server side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client side upon log out

  • Query provided token against The Blacklist on every authorized request

The Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blackblist, that will allow fast in memory access to the list. Then, in a middleware of some kind that runs on every authorized request, you should check if provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

查看更多
Explosion°爆炸
3楼-- · 2019-01-21 14:48

The JWT is stored on browser, so remove the token deleting the cookie at client side

If you need also to invalidate the token from server side before its expiration time, for example account deleted/blocked/suspended, password changed, permissions changed, user logged out by admin, take a look at Invalidating JSON Web Tokens for some commons techniques like creating a blacklist or rotating tokens

查看更多
登录 后发表回答