我是节点初学者,遇到以下问题。我使用 express、socket.io 和 passport 以及 passport.socketio 和 MongoStore。
我需要使用护照验证socket.io(我为此使用passport.socketio),但即使成功登录,握手也总是未经授权。到目前为止,这是我的代码:
var http = require('http')
var socketio = require('socket.io')
var express = require('express')
var stylus = require('stylus')
var passport = require('passport')
var passportSocketIo = require('passport.socketio')
var LocalStrategy = require('passport-local').Strategy
var mongo = require('mongoskin')
var MongoStore = require('connect-mongo')(express)
var DB = mongo.db('mongo://127.0.0.1/accounts', {safe:false})
DB.bind('accounts')
DB.bind('SessionStore')
SessionStore = new MongoStore({ db: 'SessionStore' })
var app = express()
app.configure(function () {
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.cookieParser())
app.use(express.bodyParser())
app.use(express.session({
secret: 'somekey',
store: SessionStore
}));
app.use(passport.initialize())
app.use(passport.session())
app.use(app.router)
})
这是我登录的地方:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login_failed',
failureFlash: false }))
在这里,我尝试访问需要授权的页面('/content'):
app.get('/content', ensureAuthenticated, function(req, res){
res.render('content', { user: req.user })
})
var server = http.createServer(app).listen(5050)
var io = socketio.listen(server)
io.set('authorization', passportSocketIo.authorize({
cookieParser: express.cookieParser,
key: 'express.sid',
secret: 'somekey',
store: SessionStore,
fail: function(data, accept) {
accept(null, false);
},
success: function(data, accept) {
accept(null, true);
}
}))
但是如果客户端现在尝试访问“/content”,服务器总是响应“握手未授权”:
// on client side
socket = io.connect('http://localhost:5050');
// on server side
io.sockets.on( 'connection', function( socket ) {
console.log(socket.handshake.user._id)
}
-> handshake unauthorized
有谁知道我在这里做错了什么?