Setup Token Authentication

Learn how to register a user and authenticate on login using a token

Authentication / Token

Overview

What is authentication?

In order to gain access, users must prove to the website that they are who they say they are. The ID and key are enough to confirm the user’s identity, which will allow the system to authorize the user

It’s important to note that authorization is what dictates what users are able to see and do when they log in.

To put it simply, user authentication has three tasks:

  • Manage the connection between the human (user) and the website’s server (computer).

  • Verify users’ identities.

  • Approve (or decline) the authentication so the system can move to authorizing the user.

In our case a user registers with an email and password, those are their unique keys. In order for a user to login they must submit these two values. When they do the server responds with a key, or token for that session. A token is just a really long unique string for that user’s session with the app. A new token is generated each time a user logs in.

From loopback’s explorer POST request to appUsers endpoint

Successful register response. The id property with the long string is the token

We are going to change our backend to make this more clear. So we get an actual token property instead of an id.

common/models/app-user.js

Put this code in your: app.user.js

Appuser.afterRemote('login',async(ctx, user, next)=>{
    if (user) {
        user.token = user.id;
    }
})

The above code is just adding the property token to the response we get on a successful login. Now within the same file, modify your register endpoint so we can register and receive a token in the same step vs registering then having to login. Below the code you just pasted add the following. app.user.js

Appuser.observe('after save', function(ctx, next) {
  if (ctx.isNewInstance === true) {
    var instance = ctx.instance;
     instance.createAccessToken(1209600000, 
      function(err, response){
        if (err === null) {
           ctx.instance['userId'] = response.userId
           ctx.instance["token"] = response.id;
         }
          next();
       });
        }
        else {
            next();
        }
    });

Now save app.user.js and restart your backend.

In the explorer register a user by going to the POST route Create a new instance of model Loopback explorer register route

Our register response now has a token. Note id and token are the same thing. Now check appUsers/login route

Storing Token

Session Storage Documentation Session storage have nothing angular or loopback but is on the DOM or apart of the browser. Saving token and userId to our browser’s session storage On response from login and register you will need to save your token and userId.

subscribe( res => {
   sessionStorage.setItem('token', res.token);
   sessionStorage.setItem('userId', res.userId);
})

Retrieving Token let token = sessionStorage.getItem("token”); let userId = sessionStorage.getItem("userId”);

Using the Token

When we want to authenticate that our user has access to these respective API endpoints on the backend, we need to pass the access token as part of the url.

Re-enable authentication if not already done:

module.exports = function enableAuthentication(server) {
  // enable authentication
  server.enableAuth();
};

Example:

import { Injectable } from '@angular/core';
import { HttpClient }  from '@angular/common/http';

@Injectable()
export class ApiService {

  constructor(public _http : HttpClient) { }

  baseUrl: string = 'https://swapi.co/api';

  getPlanets( ) {
    let token = sessionStorage.getItem("token”)
    return this._http.get(`${this.baseUrl}
      /planets/?accesstoken=${token}`);
  }
}

Last updated