In order to access the API as an authenticated user, we need to have an access token. We can create an access token by logging into the API. Because we don't have a user yet, we first need to create one. In the API Explorer, we go to the post/users endpoint.
In the data field, we enter a JSON object that has an email and password property. When we hit Try It Out, we see that the user got created.
Now, if we scroll all the way down, we see that there's a /user/login endpoint. When we enter the same credentials and we hit Try It Out, we see that we got a valid response. The actual response body of the API is our access token that got created. We can use the ID fields of these results to identify ourselves.
We copy the ID and paste it in the box in the top right corner. We can now make authenticated requests to the API. When we go to the /post/categories endpoints and we try to add a new category, we see that this works as expected.
If we remove the access token and we try it again, we see that we get an authorization required error message.
To have our API create an access token on start, we can use a boot script. In our project, we run LB bootscript and as a name, we enter createAccessToken. As a type, we select async. When we open our newly created script, we remove the code that got generated.
The first things we want to include is a reference to the access token and the user model. We set three variables -- email, password, and the access token that we want to have created. We start our promise chain by returning promise.resolve.
In the first then() block, we try to find the user by its email address. In the second then() block, we return the user if it got found, and otherwise, we create it using user.create. In the third then() block, we will create an access token using the variable accessToken that we set above, and the ID of the user that we got passed in as the user ID.
We then console log the ID of the generated access token to the terminal. We finalize the chain by using Bluebird's ask callback CB method to return CB. When we start our server, we see that there is an error message, "Ask callback is not a function."
To fix this, we go to the top of our boot script and require Bluebird. Because Bluebird is shipped with LoopBack 3.0we don't need to explicitly install it as a dependency. We see that our server now actually starts and that our creative access token got printed in the terminal.
When we go to the API Explorer, we can verify that we can use this token to authenticate.