Reputation: 601
How to create a permanent access token for a StrongLoop API. Now for every user login it creates an access token. And unnecessary entry in my db
I can increase the validity of access token(ttl) as mentioned here.
But still it will generate for new login.
Upvotes: 13
Views: 7750
Reputation: 15995
Loopback has an option that will allow you to create a permanent access token:
allowEternalTokens
Boolean Allow access tokens that never expire.
https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html#advanced-options
Here's what I did:
Enable allowEternalTokens
for the User model
In server/model-config.json:
"User": {
"dataSource": "db",
"options": {
"validateUpsert": true,
"allowEternalTokens": true
}
},
When logging in, set ttl
to -1
User.login(
{
email: email,
password: password,
ttl: -1,
},
As you've already figured out, every time you log in a new (different) access token will be created. So if you want to reuse the same access token, log in only once. You can get the access token from the AccessToken model (or directly from the database)
AccessToken.findOne(
{
where: {
userId: userId,
},
},
If you have a custom user model, you can set allowEternalTokens
directly in the model definition file. In addition, if you have a custom user model you'll also need to update the relations
of the AccessToken model (either the built-in one or your custom one if you have it) to point to the custom user model.
More info on custom user/access token models here: http://loopback.io/doc/en/lb3/Authentication-authorization-and-permissions.html#preparing-access-control-models
Upvotes: 12
Reputation: 11425
You are mixing up 2 different things. The AccessToken entry creation and the ttl value for the AccessToken.
When a user logs in a new AccessToken is created. If the user logs out the AccessToken is removed. If the user logs in 2 times, for example from 2 different devices, then you will get 2 AccessTokens, so this way the user will be able to access your app from the 2 devices simultaneously.
If the user wants to log in from the same device and he already has a valid token, your app should recognise this and log him in automatically.
Obviously if the ttl value is expired, the token will not be valid any more. This token will be removed if is tried to be used. I guess if you don't want this records in your database, you could create a custom cron job that removes expired tokens.
Regarding the permanent access token, it will require to disable the ttl value, and that is not possible at the moment for the default AccessToken model. I created a pull request to support that, if you are interested you could chime in and see if it gets merged.
Upvotes: 7