我是節點初學者,存在以下問題。我使用express,socket.io和passport以及passport.socketio和MongoStore。Passport.socketio:握手永遠是未經授權的
我需要使用護照來驗證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 }))
在這裏,我試圖訪問一個頁面(「/內容」),爲此,我需要授權:
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);
}
}))
但是,如果一個客戶端現在嘗試訪問「/內容」,服務器總是響應「握手擅自」:
// 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
有沒有人知道我在這裏做錯了什麼?