简体   繁体   中英

How to make API issue only one token per user (opened in multiple tabs)?

I have a web API in .net core 1.0 which issues JWT token(access_token) to the clients at login. Now, the token has a short expiry period(10 mins) and the client requests a new token in every 8 mins for the continuity of the session. This token is stored in the cookie in the browser at the client side. Now, this works fine if the client works in only one tab of the browser. However, if the client opens two or more tabs, every 8 minutes request for a new token is made to the API. This results in multiple requests from the same user simultaneously and my application issues token for each and every request but only one of the tokens is stored at client side cookie. But it results in multiple token out of which only single one is used throughout its lifetime.

I have tried storing the userId and token in DB and cross-checking them during API request, however, the same user in multiple tabs makes simultaneous request and the logic fails here.

How can I resolve this situation? I want my API to issue only one token per user opened in multiple tabs. Any help is appreciated.

This is tricky. If you try to store the token in the DB and not issue a fresh token until the old expires it will create a plethora of problems. Think of the case, when the user uses multiple devices. This logic won't work. There are many more cases.

And storing the JWT in the server is very redundant and counter-intuitive, IMO. One of the primary benefits of JWT is that you don't have to make a DB call everytime a protected resource is requested. The JWT itself has all the information for authorizing the user.

I believe, the solution you are looking for is throttling or rate limiting . You can limit the token issue endpoint to 1request/sec/ip (experiment and find the rate which works well). The idea is to block the concurrent requests for new token issues from the same IP and process just one of them. You can achieve this through IIS or through Attributes . Play around and see what works best for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM