Setup Token Authentication
Learn how to register a user and authenticate on login using a token
Last updated
Learn how to register a user and authenticate on login using a token
Last updated
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
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
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
Our login has a token property as well now. :)
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.
Retrieving Token
let token = sessionStorage.getItem("token”);
let userId = sessionStorage.getItem("userId”);
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:
Example: