Reputation: 1296
I am trying to develop an API backend in Sails.js.
The most basic thing which I require is authentication.
With that, I found the sails-generate-auth
generator, I have followed all the steps listed at
sails-generate-auth .
Now, when I access http://localhost:1337/register
, I see a simple registration form, same goes for login, and after logging in, I see a cookie set in my browser as sails.sid
.
After inspecting the AuthController.js
I see that it has been written for server rendered views.
How should I modify the controller/sailsApp so that it supports API based authentication.
I would ideally like to have:
A register route which would accept username and password via post with content type application/json.
Login route which would accept username and password with content-type application/json and return with a bearer token so that the frontend app can add it to its header the next time it makes a request.
All other routes under an auth ACL which would check if the bearer token is present and is verified.
Upvotes: 2
Views: 2545
Reputation: 869
Ive been using these steps for a while now.
Step 1 ( Globals ): $ npm install -g sails
Step 2 ( App ): $ sails new myApp
Step 3 ( Files ): Copy every file in https://github.com/carlospliego/sails-token-auth-setup to its corresponding folder
Step 4 ( Policies ): Add this code to your config/policies.js
'*': "hasToken",
UserController: {
"create": true
},
AuthController: {
'*': true
}
Step 5: change the value of config/tokenSecret.js
Step 6: ( Dependencies )
Your endpoints will look like this:
Here is a great guide on how to create token based authentication in sails: https://github.com/carlospliego/sails-token-auth-setup
Upvotes: 1
Reputation: 3099
In your AuthController callback function replace this:
res.redirect('/');
with this:
console.log(user);
var userID = user.id;
Passport.find({user: userID}, function(err, items){
if(err) return err;
console.log(items[0].accessToken);
// Make sure you dont give them any sensetive data
res.json({userData: user, token: items[0].accessToken});
});
// Upon successful login, send the user to the homepage were req.user
//res.redirect('/');
Now when the client sends a login/register request the server will response with a JSON response. Make sure you request the token on your other sails app actions.
Upvotes: 2