I was following the Loopback authentication documentation, all was clear and simple. Creating user via POST, logging in via POST too.
But right after that I got stuck on how to get the access token and add it to the other requests. In explorer side, you have just to copy/paste it in the token text-box and click set token. How about API side? all through the documentation, the token is taken for granted and being initialized at each method beginning like:
ACCESS_TOKEN=6Nb2ti5QEXIoDBS5FQGWIz4poRFiBCMMYJbYXSGHWuulOuy0GTEuGx2VCEVvbpBK
# Authorization Header
curl -X GET -H "Authorization: $ACCESS_TOKEN" \
http://localhost:3000/api/widgets
# Query Parameter
curl -X GET http://localhost:3000/api/widgets?access_token=$ACCESS_TOKEN
or
var USER_ID = 1;
var ACCESS_TOKEN = '6Nb2ti5QEXIoDBS5FQGWIz4poRFiBCMMYJbYXSGHWuulOuy0GTEuGx2VCEVvbpBK';
// remove just the token
var token = new AccessToken({
id: ACCESS_TOKEN
});
token.destroy();
// remove all user tokens
AccessToken.destroyAll({
userId: USER_ID
});
how to implement my app where there are different users.
I am working on a Angular 6 app and an ionic 3 app.
Authentication in loopback is pretty transparent, which is great, it takes a few time to learn to master it.
You should look at ACL (access control), doc here.
This works with Role
, (doc here), so basically, instead of managing all by yourself, you will tell loopback what type a user is (Role), and what that type of user can see and do within your app (ACL).
After that, when a request is made with an access token, loopback resolves the associated user and its role, then decides whether or not the action is permitted.
EDIT
To send a request, you add access_token
as a query parameter: http://domain/endpoint?access_token=*token*
. The token is acquired when the user logins in via the login endpoint, by the name of id
{
"id": "LZQB7CmC7pYrk6vz7Ghf9MaIFRQYmnouKFxjolZE5GP6XqLal53fyLg475a8PTC8",
"ttl": 1209600,
"created": "2018-11-05T11:31:12.110Z",
"userId": "5b8e7a47c6f12d00c5d6db29"
}
you can keep it in a local storage for later usage.