Search code examples
sessionauthenticationmergesails.jstoken

Sails.js: applying session and token authentication policies simultaniously


I am developing an application with sails.js. For the web application I use session authentication with passport. Now I also need to make my server accessibe from a mobile application, which requires token authentication. My question is the following: how can I define the policies so that sails accept SessionAuth or TokenAuth for certain routes?


Solution

  • The way sails handles policies, they are all applied one after another using AND logic. There is no way to combine them logically in other ways, like OR or more complicated combinations.

    In your case, I would expect it would be fairly easy to write a third policy that handles the "SessionAuth or TokenAuth" all in one policy. Say you have existing SessionAuth.js and TokenAuth.js policies that look like this:

    module.exports = function(req, res, next) {
        if (req.isSessionAuthorized()) {
            return next();
        }
        // handle rejected request
    };
    

    , and,

    module.exports = function(req, res, next) {
        if (req.isTokenAuthorized()) {
            return next();
        }
        // handle rejected request
    };
    

    Then you just create a third policy called SessionOrTokenAuth.js:

    module.exports = function(req, res, next) {
        if (req.isSessionAuthorized() || req.isTokenAuthorized()) {
            return next();
        }
        // handle rejected request
    };
    

    Then apply the newly created policy to the desired controller endpoints in /config/policies.js:

    SomeController: {
        '*': true,
        'sessionOnlyEndpoint': ['SessionAuth'],
        'tokenOnlyEndpoint': ['TokenAuth'],
        'anyAuthEndpoint': ['SessionOrTokenAuth'],
    }
    

    The actual checks are likely a touch more complicated, but probably not by much. Hope this helps.