通过websockets进行Sails.js + Passport.js身份验证 [英] Sails.js + Passport.js authentication through websockets

查看:60
本文介绍了通过websockets进行Sails.js + Passport.js身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将Sails.js与Passport.js一起使用时,通过websocket请求时,req对象上不存在isAuthenticated方法.

When I use Sails.js with Passport.js, the isAuthenticated method does not exist on the req object when requested through websocket.

谁能告诉我为什么会这样吗?

Could anyone tell me why this happens?

推荐答案

或者,您可以劫持'router:request'事件以插入用于套接字请求的通行证.我在"config/bootstrap.js"中执行此操作:

Alternatively, you can hijack the 'router:request' event to plug in passport for socket requests. I do this in 'config/bootstrap.js':

module.exports.bootstrap = function (cb) {

  var passport = require('passport'),
    initialize = passport.initialize(),
    session = passport.session(),
    http = require('http'),
    methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];

  sails.removeAllListeners('router:request');
  sails.on('router:request', function(req, res) {
    initialize(req, res, function () {
      session(req, res, function (err) {
        if (err) {
          return sails.config[500](500, req, res);
        }
        for (var i = 0; i < methods.length; i++) {
          req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
        }
        sails.router.route(req, res);
      });
    });
  });
  cb();
};

使用这种方法,您不需要在策略中检查套接字请求身份验证的特殊处理.您仍然需要通过快速中间件将护照用于非套接字请求.

With this approach you don't need special handling for checking socket request authentication in policies. You do still need to hook up passport for non socket requests by way of express middleware.

这篇关于通过websockets进行Sails.js + Passport.js身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆