问题
I think passport.js is a amazing framework. Unfortunately, however, it seems to be that doesn't support socket. Why I said this is that Sails framework provides http and socket. When user connected sails's service through passport.js, it doesn't matter. Accessing by socket makes error. Because socket may not support middleware?
Anyway, the critical problem, I don't know how apply passport.js on socket.
回答1:
Indeed, the websocket requests do not pass threw the passport middleware, but it is possible to use a workaround. Are you using this sails passport generator ?
I added this code to the passport policy to add passport methods to the socket requests.
/** Content not generated BEGIN */
var http = require('http')
, methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
/** Content not generated END */
module.exports = function (req, res, next) {
// Initialize Passport
passport.initialize()(req, res, function () {
// Use the built-in sessions
passport.session()(req, res, function () {
// Make the user available throughout the frontend
res.locals.user = req.user;
/** Content not generated BEGIN */
// Make the passport methods available for websocket requests
if (req.isSocket) {
for (var i = 0; i < methods.length; i++) {
req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
}
}
/** Content not generated END */
next();
});
});
};
回答2:
Alexis gave the right answer... I think it's the way recommanded by Mike, regarding this message : https://stackoverflow.com/a/17793954/6793876
Just delete passport's mentions in config/http.js , make new policy passportMiddleware.js with the following content :
//passportMiddleware.js
var passport = require('passport');
var http = require('http');
module.exports = function (req, res, next) {
// Initialize Passport
passport.initialize()(req, res, function () {
// Use the built-in sessions
passport.session()(req, res, function () {
res.locals.user = req.user;
var methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
if (req.isSocket) {
for (var i = 0; i < methods.length; i++) {
req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
}
}
next();
});
});
};
And finally add this policy to all controllers, in policies.js :
module.exports.policies = {
RabbitController: {
nurture : ['passportMiddleware','isRabbitMother'],
feed : ['passportMiddleware','isNiceToAnimals', 'hasRabbitFood']
}
};
来源:https://stackoverflow.com/questions/31373595/passport-js-doesnt-work-on-sails-socket-environment