SailsJS - using sails.io.js with JWT

十年热恋 提交于 2019-12-03 07:16:27

I realised that policy I've put in place and that was using express-jwt abstracted too much away from me, so I didn't figure out what exactly was happening. Once I looked at other examples, I've figured out that I only needed to check what's different for websocket requests than regular, and I quickly found a way around the problem.

So:

  1. set up token signing and sending on login
  2. Angular takes the token and saves to local storage
  3. Create an interceptor for HTTP requests to add authorization header and token
  4. Fix up sails.io.js to forward query parameters provided through options (as mentioned in the question)
  5. When connecting using sails.io.js, send token as query parameter, i.e. url + '?token=' + token
  6. In sails policy, check all combinations for token, including req.socket.handshake.query, as below:

    module.exports = function (req, res, next) {
    
    var token;
    
    if (req.headers && req.headers.authorization) {
    
        var parts = req.headers.authorization.split(' ');
    
        if (parts.length == 2) {
    
            var scheme = parts[0],
            credentials = parts[1];
    
            if (/^Bearer$/i.test(scheme)) {
                token = credentials;
            }
    
        } else {
            return res.json(401, {err: 'Format is Authorization: Bearer [token]'});
        }
    
    } else if (req.param('token')) {
    
        token = req.param('token');
        // We delete the token from param to not mess with blueprints
        delete req.query.token;
    
    }
    
    // If connection from socket
    else if (req.socket && req.socket.handshake && req.socket.handshake.query && req.socket.handshake.query.token) {
    
        token = req.socket.handshake.query.token;
    
    } else {
        sails.log(req.socket.handshake);
        return res.json(401, {err: 'No Authorization header was found'});
    }
    
    JWTService.verifyToken(token, function (err, token) {
    
        if (err) {
            return res.json(401, {err: 'The token is not valid'});
        }
    
        sails.log('Token valid');
    
        req.token = token;
    
        return next();
    
    });
    
    };
    

It works well! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!