JackH
JackH

Reputation: 4735

Protect API routes in Sails.js with token-based authentication?

I'm new to Sails.js. I created a new project and a few APIs using the sails generate api [name] command. These new APIs have complete CRUD functionality so I can GET, POST, PUT etc. In order to protect them, I've implemented a standard token-based authentication system that will be used by clients accessing my API. The token is also persisted in the database.

I have two questions:

  1. How do I disable certain actions on specific routes (like enable GET requests on the /user API but not on the /account API but allow POSTS on the /account API for example)
  2. I want the client to send me back the generated Access Token for every post-authentication request. When they do, how do I intercept the request and check if the token exists in the database before allowing access to the requested route?

Thank you.

Upvotes: 1

Views: 2204

Answers (2)

Carlos Pliego
Carlos Pliego

Reputation: 869

I've gone ahead and created a guide for you here: https://github.com/carlospliego/sails-token-auth-setup

Upvotes: 0

Aston
Aston

Reputation: 225

  1. You will need to create policies to prevent non-authenticated user to perform some requests. I consider here that GET /user and GET /account will be routed to a find function. And POST /account routed to a create function. In config/policies.js :

    module.exports.policies = {
     'UserController': {
      'create': 'isAuth',
      'find': true
      },
     'AccountController': {
      'create': 'isAuth',
      'find': true
      }
    }
    

    You will need to add a isAuth.js policy file in api/policies

  2. To authenticate user in Sails, I use (as many others) passportjs. You will define auth strategies. It is a powerful tool and will allow you to create custom auth strategies or use OAuth2 protocol if you need (if you use token you should use it).

Sails does exactly intercept every requests and execute the policy you configured for the routed action.

You will be able to find some documentation on the Internet on Sails, Policies, Passport, Oauth2.

Hope I have helped you.

Upvotes: 2

Related Questions