7

I am using laravel sanctum for API authentication for my mobile app.

How can we limit the maximum number of active tokens per user?

Currently, in the personal_access_tokens sanctum generated table, there is no user_id reference. With the current table, imagine if a user logs in and logs out unlimitedly. We will have N number of new tokens created in the table.

enter image description here

  1. Is there a default way of limiting the total number of tokens per user out of the box or this needs to be done on my own?
  2. Is this a good practice to have new rows of tokens added to the DB table on every new login?
Manas
  • 3,060
  • 4
  • 27
  • 55

1 Answers1

6

There is a reference to user, namely tokenable_type and tokenable_id. Which in this case references App\Models\User and the user ID in the tokenable_id.

Somewhere in your application, you are creating these tokens for that specific user. You have the choice here to issue new tokens for every login session, but you could also demand the user to use an old token. That is up to you and the use case of the application.

However, if you are creating new tokens for every login session, consider revoking old tokens (since they will probably not be used anymore). Check the Sanctum documentation.

Tokens are valid for as long as defined in: config/sanctum.php in the expiration key. Standard, personal access tokens do not expire because the expiration key is set to null.

Answering your questions:

  1. Yes, you can simply get the amount of tokens using $user->tokens()->count(); and do whatever you want to do with it (removing old tokens, or returning an error).
  2. This answer depends on your use case. If tokens are valid forever, why would you create a new one on every login, instead of demanding the token that is still valid? Alternatively, you could create a form for the user to request a new token if they forgot their old one, removing the old token and issuing a new one. This way, all tokens in the DB are valid.
Eric Landheer
  • 2,033
  • 1
  • 11
  • 25
  • 1
    Thank you! I overlooked the `takenable_type` and `tokenable_id`, it all makes sense now! I think I will just stick to having one token per user. For the very first time user logs in, I just need to check for an existing token or else create one. The other concern I had on deleting the token upon user logging out, but I guess I will keep the token for that user, because chances are users could be using the application from multiple devices like iphone and ipad as the token will be saved locally. – Manas Jul 15 '21 at 15:26
  • 1
    But we are not sure about devices. Remove which token. Maybe user has 3 different devices logged in. – Ozal Zarbaliyev Sep 08 '22 at 11:20