Loopback - How to create a custom time based access token for a user?

Its been only two days that I have started writing technical blog posts on Loopback.io and today I got a mail from a person in Finland, Helsinki who found my last blog post on "Loopback.io - How to get the current access token / user id in a remote method ?" to be useful. I never thought that the response would be this quick but its great for motivating me to write more. I am still in the process of migrating my posts from my old blog so keep an eye.

The person mentioned asked me some more questions and the title of this blog post addresses one of that.

So "How would you create a custom time based access token for a user?". Any guesses?

The only problem with Loopback is that it allows you to do all sort of things but sadly some of the things are not properly documented. So I will first explain you how I figured this thing out and then I will share the code.

Lets start

By default, Loopback creates a User model which allows one to register and login. I assume that you can create a new user by registering the user to POST /Users with required data or by writing it in the code.
When a User logins, a new access token is created.
So I dived into the User model API docs and used the API Explorer to find out the parameters for the /Users/login endpoint.

I found that it takes a credentials object. Now again there is no documentation for the credentials object or I couldn't find it using Google. Then I decided to take the hard option i.e. I dived into the source code of Loopback framework. It may sound a bit scary for some of you but beleive me, its simple to understand if you are willing to and you can understand some basic JS.

I opened common/models/user.js in the source code and then looked at the source code of the login method. By reading the source code, I found that I can pass the ttl value in the credentials object, see here.

Now if you do a request to POST /Users/login with the credentials object(try this in API explorer)

POST /Users/login  
{
"email":"foo@bar.com",
"password":"foobar",
"ttl": 30000
}

It will create the access token with ttl equals to 30 sec.
Yay, we got the solution to the problem, not yet.

You as a good backend API designer will not leave the responsibility on the end user to specify the ttl of the access token. You would want to set it on your own server.
Now that I know that if I can modify the credentials object to include a ttl field, I can set the expiration time of access tokens. To achieve that, we can create a beforeRemote hook for the login method and can inject the ttl field into the credential object.

I have left the implementation of the beforeRemote hook because it would be trivial to do after you have learnt remote hooks(see the sample examples in the official docs).

For any discussion/doubts on this, leave comments below this post.

comments powered by Disqus