0

I have a React app that connects to a REST API for which I have to implement token based authentication. The only info stored in the token is the user id.

The following flow will be used:

  • User logs in, server sets the token and the refresh token in HttpOnly cookies.
  • On each request the server will check the validity of the token and the database will be queried to pull the user info.
  • If the token is expired, the refresh token will be used to get a new one.

I was thinking to check the user in the database on each request so I can invalidate the account instantly. Are there any problems with this flow?

1 Answer 1

0

I was thinking to check the user in the database on each request so I can invalidate the account instantly. Are there any problems with this flow?

I don't see anything glaringly wrong, but....

There are some downsides. Doing this, requires that every user-interaction lookup your database table. For a small-ish application with not many users, this shouldn't prove a problem. If you've got thousands of users, with thousands of interactions per hour, that's millions of user lookups. Can you database handle this?

The alternative, would be to do this check only when the token is refreshed instead -- that way, you look up the database only once per refresh interval (let's say 15 minutes). Then 1,000 concurrent users will only result in a maximum of 4,000 lookups of the user table per hour (something any db can handle). This also means that only one service in your app (the refresh end point) needs access to the user table, which gives you better control and granularity for protecting your sensitive user data.

Of course, this means that if you need to disable a user, the worst-case scenario you can do this in is 15 minutes. For some applications that might not be acceptable -- so falling back to your check per request might prove a better solution if indeed this is a requirement.

In short, I don't think there's anything wrong with this approach, but I wouldn't recommend it. Do the user check on refresh instead of every request, tokens were built so that every end-point/micro-service could authenticate the user token without having to go back to a singular database table or end-point.

3
  • If I store just the user id in the token, don't I have to make a db query on each request to pull info about the user anyways? For example in my app each user has a balance which can change faster than the token expires.
    – civ15
    Nov 23, 2019 at 1:54
  • Correct, but you'd be pulling data from a different table for that, not the user table. Nov 23, 2019 at 8:11
  • What difference does it make if I pull the data from the user table or from a different table?
    – civ15
    Nov 23, 2019 at 15:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .