Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Permanent AccessToken in loopback

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.

like image 483
Rameez Avatar asked Sep 23 '15 11:09

Rameez


People also ask

What is access token in REST API?

Access tokens are used in token-based authentication to allow an application to access an API. The application receives an access token after a user successfully authenticates and authorizes access, then passes the access token as a credential when it calls the target API.


1 Answers

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:

  1. Enable allowEternalTokens for the User model

    In server/model-config.json:

    "User": {
      "dataSource": "db",
      "options": {
        "validateUpsert": true,
        "allowEternalTokens": true
      }
    },
    
  2. When logging in, set ttl to -1

    User.login(
    {
      email: email,
      password: password,
      ttl: -1,
    },
    
  3. 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

like image 59
bmaupin Avatar answered Sep 18 '22 16:09

bmaupin