/ nodejs

How to use JSON web token authentication with Sails.js

Using JSON webtoken authentication for consuming rest-api from your Single Page Application is pretty common these days.

In this post I'll be helping you to use it in your Sails.js App. Well'll be using simplest user name and password for user sign-up/in.

Prerequisite: I am assuming you have a sails app with a User model. You need to run npm i jsonwebtoken bcrypt --save to get necessary dependencies for this tutorial.

First of all we need to create a service called "jwToken".
api/services/jwToken.js :

Users model at api/models/Users.js :

Next, we override "create" action for user sign-up.
api/controllers/UsersController.js:

We need a controller to authenticate/login users.
api/controllers/AuthController.js:

Now let's create a isAuthorized policy to check if a user has valid token in the request header.
api/policies/isAuthorized.js:

Then we use config/policies.js to protect our controllers :

Now we are ready to test! Lift the sails and fire up Postman.
Send a get request to /users:

{
"err": "No Authorization header was found"
}

Ok! Now lets create a user by sending a post request to /users with email, password & confirmPassword:

{
"user": {
"email": "email@mail.mail",
"createdAt": "2015-04-26T10:02:15.774Z",
"updatedAt": "2015-04-26T10:02:15.774Z",
"id": 2
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MiwiaWF0IjoxNDMwMDQyNTM1LCJleHAiOjE0MzAwNTMzMzV9.rDr89JFZtZnTq4Zv8T2ZET0FgVy59ezRYLWXw75VnF0"
}

We got the token!
Once again send a get request to /users with a Authorization header with a value of Bearer [paste the token] :

[ 
{
"email": "email@mail.mail",
"createdAt": "2015-04-26T10:02:15.774Z",
"updatedAt": "2015-04-26T10:02:15.774Z",
"id": 1
}
]

Yes, it works.

Q. How to get it worikng with angular?
A. Here is a great example by Rodríguez.

Got a question or suggestion? Feel free to leave it bellow :).