This tutorial is related to "Create RESTful API in less than 5 minutes with sailsjs". And i'm forgot to mention which version of sailsjs, i'm using sails ~0.11.x when i writing this blog.
Before we going further, if you are following my previous tutorial and not creating new project for this tutorial, then you need to delete user model under
api/models/, because we are gonna using npm
sails-generate-authwhich will automatically create a user model for us.
Install the packages
You can just following this section or looking at to the original documentation
- Install authentication generator
npm install sails-generate-auth
- Run the auth generator
sails generate auth
the command above will generate boilerplate that need it for authentications as shown below:
- then we need to add the following line on
config/bootstrap.jsin order to load your Passport on startup:
And also add routes,
- add the policies of the authentication,
config/policies.js, like so:
- Next, we need to install passport, bcryptjs and validator packages from npm.
npm install passport
npm install bcryptjs
npm install validator
If you check on
config/passport.jsyou will see all authentication prepared for you by
sails-generate-auth, but in this tutorial we are only need
passport-http-bearer, so its up to you whether you're gonna install all of it or not, but i'll just install these and commend the rest of it.
npm install passport-local
npm install passport-http-bearer
and now we're done for installing packages and it's time for testing our authentication.
Running the API auth
First, we need to create controller for our user model, api/controllers/UserController.js.
Then, we need to modified our
config/policies.js like so:
sails list and choose
prompt: 3 to clean our previous data.
http://localhost:1337/registerand registering your username, email, and password (alphanumeric). In this process, by default the system will generate your accessToken and hashing your password.
- You can do login test using your registered data in:
- And if you want to access your user data without login (just like Restful API), all you need to do is access_token which already generated for you. To know what is your access token, remove
bearerAuthtemporary and restart your server, and type
http://localhost:1337/userand save the access_token.
- Put back
bearerAuthagain, and restart the server. And now you can access your user data using access_token, like so:
Congratulation! We did it!!