我正在设置一台同时使用socketio和express的服务器。我已经尽了一切努力,可以使用护照作为中间件在两者之间共享会话并进行快速会话,并且由于无法使它工作,我正在向社区寻求帮助。
我尝试了很多事情,并遵循了很多教程。他们总是最终在“连接”回调中在socketio内部获得通行证会话。
我按以下顺序调用所有内容。我首先设置快速会话:
private SetupMiddleware(): void {
this.app.use(logger("dev"));
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.cookieParser = cookieParser();
this.app.use(this.cookieParser);
this.app.use(fileUpload());
// See https://medium.com/@evangow/server-authentication-basics-express-sessions-passport-and-curl-359b7456003d
this.session = session({
name: "trial",
cookie: { maxAge: Application.maxAge },
resave: false,
saveUninitialized: true,
secret: "joejeep",
});
this.app.use(this.session);
this.io.use((socket, next) => {
this.session(socket.request, socket.request.res, next);
});
}
然后我设置护照:
private SetupAuth(): void {
passport.use(new LocalStrategy.Strategy(
(username, password, done) => {
databaseService.CheckUserCredentials(username, password).then((res) => {
if (res) {
return done(null, username);
} else {
return done(null, false, { message: "Incorrect password." });
}
}).catch((err) => {
return done(null, false, { message: "Could not find username '" + username + "'." });
});
},
));
passport.serializeUser((user, done) => {
// TODO: Replace this with the actual user id
done(null, user);
});
passport.deserializeUser((id, done) => {
// I also noticed I can never reach this point
done(null, id);
});
this.passInit = passport.initialize();
this.passSess = passport.session();
this.app.use(this.passInit);
this.app.use(this.passSess);
this.io.use((socket, next) => {
this.passInit(socket.request, socket.request.res, next);
});
this.io.use((socket, next) => {
this.passSess(socket.request, socket.request.res, next);
});
}
最后,我设置了套接字:
private SetupSocket(): void {
this.io.on("connection", (socket) => {
if (socket.request.session.passport) {
//unable to reach here
}
});
}
我面临的问题是,连接后我无法在插槽内获取护照对象。
io.on(“ connection” ...中的console.log(socket.request)的输出...
IncomingMessage {
[1] _readableState:
[1] ReadableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] buffer: BufferList { head: null, tail: null, length: 0 },
[1] length: 0,
[1] pipes: null,
[1] pipesCount: 0,
[1] flowing: true,
[1] ended: true,
[1] endEmitted: false,
[1] reading: false,
[1] sync: true,
[1] needReadable: false,
[1] emittedReadable: true,
[1] readableListening: false,
[1] resumeScheduled: true,
[1] destroyed: false,
[1] defaultEncoding: 'utf8',
[1] awaitDrain: 0,
[1] readingMore: true,
[1] decoder: null,
[1] encoding: null },
[1] readable: true,
[1] domain: null,
[1] _events: {},
[1] _eventsCount: 0,
[1] _maxListeners: undefined,
[1] socket:
[1] Socket {
[1] connecting: false,
[1] _hadError: false,
[1] _handle:
[1] TCP {
[1] reading: true,
[1] owner: [Circular],
[1] onread: [Function: onread],
[1] onconnection: null,
[1] writeQueueSize: 0,
[1] _consumed: true },
[1] _parent: null,
[1] _host: null,
[1] _readableState:
[1] ReadableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] buffer: [Object],
[1] length: 0,
[1] pipes: null,
[1] pipesCount: 0,
[1] flowing: true,
[1] ended: false,
[1] endEmitted: false,
[1] reading: true,
[1] sync: false,
[1] needReadable: true,
[1] emittedReadable: false,
[1] readableListening: false,
[1] resumeScheduled: false,
[1] destroyed: false,
[1] defaultEncoding: 'utf8',
[1] awaitDrain: 0,
[1] readingMore: false,
[1] decoder: null,
[1] encoding: null },
[1] readable: true,
[1] domain: null,
[1] _events:
[1] { end: [Array],
[1] finish: [Function: onSocketFinish],
[1] _socketEnd: [Function: onSocketEnd],
[1] drain: [Array],
[1] timeout: [Function: socketOnTimeout],
[1] data: [Function: bound socketOnData],
[1] error: [Function: socketOnError],
[1] close: [Function: bound socketOnClose],
[1] resume: [Function: onSocketResume],
[1] pause: [Function: onSocketPause] },
[1] _eventsCount: 10,
[1] _maxListeners: undefined,
[1] _writableState:
[1] WritableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] finalCalled: false,
[1] needDrain: false,
[1] ending: false,
[1] ended: false,
[1] finished: false,
[1] destroyed: false,
[1] decodeStrings: false,
[1] defaultEncoding: 'utf8',
[1] length: 0,
[1] writing: false,
[1] corked: 0,
[1] sync: false,
[1] bufferProcessing: false,
[1] onwrite: [Function: bound onwrite],
[1] writecb: null,
[1] writelen: 0,
[1] bufferedRequest: null,
[1] lastBufferedRequest: null,
[1] pendingcb: 0,
[1] prefinished: false,
[1] errorEmitted: false,
[1] bufferedRequestCount: 0,
[1] corkedRequestsFree: [Object] },
[1] writable: true,
[1] allowHalfOpen: true,
[1] _bytesDispatched: 327,
[1] _sockname: null,
[1] _pendingData: null,
[1] _pendingEncoding: '',
[1] server:
[1] Server {
[1] domain: null,
[1] _events: [Object],
[1] _eventsCount: 6,
[1] _maxListeners: undefined,
[1] _connections: 1,
[1] _handle: [Object],
[1] _usingSlaves: false,
[1] _slaves: [],
[1] _unref: false,
[1] allowHalfOpen: true,
[1] pauseOnConnect: false,
[1] httpAllowHalfOpen: false,
[1] timeout: 120000,
[1] keepAliveTimeout: 5000,
[1] _pendingResponseData: 0,
[1] maxHeadersCount: null,
[1] _connectionKey: '6::::5000',
[1] [Symbol(asyncId)]: 16 },
[1] _server:
[1] Server {
[1] domain: null,
[1] _events: [Object],
[1] _eventsCount: 6,
[1] _maxListeners: undefined,
[1] _connections: 1,
[1] _handle: [Object],
[1] _usingSlaves: false,
[1] _slaves: [],
[1] _unref: false,
[1] allowHalfOpen: true,
[1] pauseOnConnect: false,
[1] httpAllowHalfOpen: false,
[1] timeout: 120000,
[1] keepAliveTimeout: 5000,
[1] _pendingResponseData: 0,
[1] maxHeadersCount: null,
[1] _connectionKey: '6::::5000',
[1] [Symbol(asyncId)]: 16 },
[1] _idleTimeout: 5000,
[1] _idleNext:
[1] TimersList {
[1] _idleNext: [Circular],
[1] _idlePrev: [Circular],
[1] _timer: [Object],
[1] _unrefed: true,
[1] msecs: 5000,
[1] nextTick: false },
[1] _idlePrev:
[1] TimersList {
[1] _idleNext: [Circular],
[1] _idlePrev: [Circular],
[1] _timer: [Object],
[1] _unrefed: true,
[1] msecs: 5000,
[1] nextTick: false },
[1] _idleStart: 39763,
[1] _destroyed: false,
[1] parser:
[1] HTTPParser {
[1] '0': [Function: parserOnHeaders],
[1] '1': [Function: parserOnHeadersComplete],
[1] '2': [Function: parserOnBody],
[1] '3': [Function: parserOnMessageComplete],
[1] '4': [Function: bound onParserExecute],
[1] _headers: [],
[1] _url: '',
[1] _consumed: true,
[1] socket: [Circular],
[1] incoming: [Circular],
[1] outgoing: null,
[1] maxHeaderPairs: 2000,
[1] onIncoming: [Function: bound parserOnIncoming] },
[1] on: [Function: socketOnWrap],
[1] _paused: false,
[1] read: [Function],
[1] _consuming: true,
[1] _httpMessage: null,
[1] _peername: { address: '::ffff:127.0.0.1', family: 'IPv6', port: 57937 },
[1] [Symbol(asyncId)]: 113,
[1] [Symbol(bytesRead)]: 0,
[1] [Symbol(asyncId)]: 114,
[1] [Symbol(triggerAsyncId)]: 113 },
[1] connection:
[1] Socket {
[1] connecting: false,
[1] _hadError: false,
[1] _handle:
[1] TCP {
[1] reading: true,
[1] owner: [Circular],
[1] onread: [Function: onread],
[1] onconnection: null,
[1] writeQueueSize: 0,
[1] _consumed: true },
[1] _parent: null,
[1] _host: null,
[1] _readableState:
[1] ReadableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] buffer: [Object],
[1] length: 0,
[1] pipes: null,
[1] pipesCount: 0,
[1] flowing: true,
[1] ended: false,
[1] endEmitted: false,
[1] reading: true,
[1] sync: false,
[1] needReadable: true,
[1] emittedReadable: false,
[1] readableListening: false,
[1] resumeScheduled: false,
[1] destroyed: false,
[1] defaultEncoding: 'utf8',
[1] awaitDrain: 0,
[1] readingMore: false,
[1] decoder: null,
[1] encoding: null },
[1] readable: true,
[1] domain: null,
[1] _events:
[1] { end: [Array],
[1] finish: [Function: onSocketFinish],
[1] _socketEnd: [Function: onSocketEnd],
[1] drain: [Array],
[1] timeout: [Function: socketOnTimeout],
[1] data: [Function: bound socketOnData],
[1] error: [Function: socketOnError],
[1] close: [Function: bound socketOnClose],
[1] resume: [Function: onSocketResume],
[1] pause: [Function: onSocketPause] },
[1] _eventsCount: 10,
[1] _maxListeners: undefined,
[1] _writableState:
[1] WritableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] finalCalled: false,
[1] needDrain: false,
[1] ending: false,
[1] ended: false,
[1] finished: false,
[1] destroyed: false,
[1] decodeStrings: false,
[1] defaultEncoding: 'utf8',
[1] length: 0,
[1] writing: false,
[1] corked: 0,
[1] sync: false,
[1] bufferProcessing: false,
[1] onwrite: [Function: bound onwrite],
[1] writecb: null,
[1] writelen: 0,
[1] bufferedRequest: null,
[1] lastBufferedRequest: null,
[1] pendingcb: 0,
[1] prefinished: false,
[1] errorEmitted: false,
[1] bufferedRequestCount: 0,
[1] corkedRequestsFree: [Object] },
[1] writable: true,
[1] allowHalfOpen: true,
[1] _bytesDispatched: 327,
[1] _sockname: null,
[1] _pendingData: null,
[1] _pendingEncoding: '',
[1] server:
[1] Server {
[1] domain: null,
[1] _events: [Object],
[1] _eventsCount: 6,
[1] _maxListeners: undefined,
[1] _connections: 1,
[1] _handle: [Object],
[1] _usingSlaves: false,
[1] _slaves: [],
[1] _unref: false,
[1] allowHalfOpen: true,
[1] pauseOnConnect: false,
[1] httpAllowHalfOpen: false,
[1] timeout: 120000,
[1] keepAliveTimeout: 5000,
[1] _pendingResponseData: 0,
[1] maxHeadersCount: null,
[1] _connectionKey: '6::::5000',
[1] [Symbol(asyncId)]: 16 },
[1] _server:
[1] Server {
[1] domain: null,
[1] _events: [Object],
[1] _eventsCount: 6,
[1] _maxListeners: undefined,
[1] _connections: 1,
[1] _handle: [Object],
[1] _usingSlaves: false,
[1] _slaves: [],
[1] _unref: false,
[1] allowHalfOpen: true,
[1] pauseOnConnect: false,
[1] httpAllowHalfOpen: false,
[1] timeout: 120000,
[1] keepAliveTimeout: 5000,
[1] _pendingResponseData: 0,
[1] maxHeadersCount: null,
[1] _connectionKey: '6::::5000',
[1] [Symbol(asyncId)]: 16 },
[1] _idleTimeout: 5000,
[1] _idleNext:
[1] TimersList {
[1] _idleNext: [Circular],
[1] _idlePrev: [Circular],
[1] _timer: [Object],
[1] _unrefed: true,
[1] msecs: 5000,
[1] nextTick: false },
[1] _idlePrev:
[1] TimersList {
[1] _idleNext: [Circular],
[1] _idlePrev: [Circular],
[1] _timer: [Object],
[1] _unrefed: true,
[1] msecs: 5000,
[1] nextTick: false },
[1] _idleStart: 39763,
[1] _destroyed: false,
[1] parser:
[1] HTTPParser {
[1] '0': [Function: parserOnHeaders],
[1] '1': [Function: parserOnHeadersComplete],
[1] '2': [Function: parserOnBody],
[1] '3': [Function: parserOnMessageComplete],
[1] '4': [Function: bound onParserExecute],
[1] _headers: [],
[1] _url: '',
[1] _consumed: true,
[1] socket: [Circular],
[1] incoming: [Circular],
[1] outgoing: null,
[1] maxHeaderPairs: 2000,
[1] onIncoming: [Function: bound parserOnIncoming] },
[1] on: [Function: socketOnWrap],
[1] _paused: false,
[1] read: [Function],
[1] _consuming: true,
[1] _httpMessage: null,
[1] _peername: { address: '::ffff:127.0.0.1', family: 'IPv6', port: 57937 },
[1] [Symbol(asyncId)]: 113,
[1] [Symbol(bytesRead)]: 0,
[1] [Symbol(asyncId)]: 114,
[1] [Symbol(triggerAsyncId)]: 113 },
[1] httpVersionMajor: 1,
[1] httpVersionMinor: 1,
[1] httpVersion: '1.1',
[1] complete: true,
[1] headers:
[1] { host: 'localhost:5000',
[1] accept: '*/*',
[1] connection: 'keep-alive',
[1] 'accept-encoding': 'gzip, deflate',
[1] 'user-agent': 'python-requests/2.13.0',
[1] cookie: 's%3AlPJ4Jj8EI0VqkaPlE17-Fz6F3ipgY7GN.hhpf9p%2FPGfxy%2BRnrGZlw1qiuNZm9eqZEJQuCsG0967s' },
[1] rawHeaders:
[1] [ 'Host',
[1] 'localhost:5000',
[1] 'Accept',
[1] '*/*',
[1] 'Connection',
[1] 'keep-alive',
[1] 'Accept-Encoding',
[1] 'gzip, deflate',
[1] 'User-Agent',
[1] 'python-requests/2.13.0',
[1] 'cookie',
[1] 's%3AlPJ4Jj8EI0VqkaPlE17-Fz6F3ipgY7GN.hhpf9p%2FPGfxy%2BRnrGZlw1qiuNZm9eqZEJQuCsG0967s' ],
[1] trailers: {},
[1] rawTrailers: [],
[1] upgrade: false,
[1] url: '/socket.io/?transport=polling&EIO=3&t=1554861396.1907172',
[1] method: 'GET',
[1] statusCode: null,
[1] statusMessage: null,
[1] client:
[1] Socket {
[1] connecting: false,
[1] _hadError: false,
[1] _handle:
[1] TCP {
[1] reading: true,
[1] owner: [Circular],
[1] onread: [Function: onread],
[1] onconnection: null,
[1] writeQueueSize: 0,
[1] _consumed: true },
[1] _parent: null,
[1] _host: null,
[1] _readableState:
[1] ReadableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] buffer: [Object],
[1] length: 0,
[1] pipes: null,
[1] pipesCount: 0,
[1] flowing: true,
[1] ended: false,
[1] endEmitted: false,
[1] reading: true,
[1] sync: false,
[1] needReadable: true,
[1] emittedReadable: false,
[1] readableListening: false,
[1] resumeScheduled: false,
[1] destroyed: false,
[1] defaultEncoding: 'utf8',
[1] awaitDrain: 0,
[1] readingMore: false,
[1] decoder: null,
[1] encoding: null },
[1] readable: true,
[1] domain: null,
[1] _events:
[1] { end: [Array],
[1] finish: [Function: onSocketFinish],
[1] _socketEnd: [Function: onSocketEnd],
[1] drain: [Array],
[1] timeout: [Function: socketOnTimeout],
[1] data: [Function: bound socketOnData],
[1] error: [Function: socketOnError],
[1] close: [Function: bound socketOnClose],
[1] resume: [Function: onSocketResume],
[1] pause: [Function: onSocketPause] },
[1] _eventsCount: 10,
[1] _maxListeners: undefined,
[1] _writableState:
[1] WritableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] finalCalled: false,
[1] needDrain: false,
[1] ending: false,
[1] ended: false,
[1] finished: false,
[1] destroyed: false,
[1] decodeStrings: false,
[1] defaultEncoding: 'utf8',
[1] length: 0,
[1] writing: false,
[1] corked: 0,
[1] sync: false,
[1] bufferProcessing: false,
[1] onwrite: [Function: bound onwrite],
[1] writecb: null,
[1] writelen: 0,
[1] bufferedRequest: null,
[1] lastBufferedRequest: null,
[1] pendingcb: 0,
[1] prefinished: false,
[1] errorEmitted: false,
[1] bufferedRequestCount: 0,
[1] corkedRequestsFree: [Object] },
[1] writable: true,
[1] allowHalfOpen: true,
[1] _bytesDispatched: 327,
[1] _sockname: null,
[1] _pendingData: null,
[1] _pendingEncoding: '',
[1] server:
[1] Server {
[1] domain: null,
[1] _events: [Object],
[1] _eventsCount: 6,
[1] _maxListeners: undefined,
[1] _connections: 1,
[1] _handle: [Object],
[1] _usingSlaves: false,
[1] _slaves: [],
[1] _unref: false,
[1] allowHalfOpen: true,
[1] pauseOnConnect: false,
[1] httpAllowHalfOpen: false,
[1] timeout: 120000,
[1] keepAliveTimeout: 5000,
[1] _pendingResponseData: 0,
[1] maxHeadersCount: null,
[1] _connectionKey: '6::::5000',
[1] [Symbol(asyncId)]: 16 },
[1] _server:
[1] Server {
[1] domain: null,
[1] _events: [Object],
[1] _eventsCount: 6,
[1] _maxListeners: undefined,
[1] _connections: 1,
[1] _handle: [Object],
[1] _usingSlaves: false,
[1] _slaves: [],
[1] _unref: false,
[1] allowHalfOpen: true,
[1] pauseOnConnect: false,
[1] httpAllowHalfOpen: false,
[1] timeout: 120000,
[1] keepAliveTimeout: 5000,
[1] _pendingResponseData: 0,
[1] maxHeadersCount: null,
[1] _connectionKey: '6::::5000',
[1] [Symbol(asyncId)]: 16 },
[1] _idleTimeout: 5000,
[1] _idleNext:
[1] TimersList {
[1] _idleNext: [Circular],
[1] _idlePrev: [Circular],
[1] _timer: [Object],
[1] _unrefed: true,
[1] msecs: 5000,
[1] nextTick: false },
[1] _idlePrev:
[1] TimersList {
[1] _idleNext: [Circular],
[1] _idlePrev: [Circular],
[1] _timer: [Object],
[1] _unrefed: true,
[1] msecs: 5000,
[1] nextTick: false },
[1] _idleStart: 39763,
[1] _destroyed: false,
[1] parser:
[1] HTTPParser {
[1] '0': [Function: parserOnHeaders],
[1] '1': [Function: parserOnHeadersComplete],
[1] '2': [Function: parserOnBody],
[1] '3': [Function: parserOnMessageComplete],
[1] '4': [Function: bound onParserExecute],
[1] _headers: [],
[1] _url: '',
[1] _consumed: true,
[1] socket: [Circular],
[1] incoming: [Circular],
[1] outgoing: null,
[1] maxHeaderPairs: 2000,
[1] onIncoming: [Function: bound parserOnIncoming] },
[1] on: [Function: socketOnWrap],
[1] _paused: false,
[1] read: [Function],
[1] _consuming: true,
[1] _httpMessage: null,
[1] _peername: { address: '::ffff:127.0.0.1', family: 'IPv6', port: 57937 },
[1] [Symbol(asyncId)]: 113,
[1] [Symbol(bytesRead)]: 0,
[1] [Symbol(asyncId)]: 114,
[1] [Symbol(triggerAsyncId)]: 113 },
[1] _consuming: false,
[1] _dumped: true,
[1] _query: { transport: 'polling', EIO: '3', t: '1554861396.1907172' },
[1] res:
[1] ServerResponse {
[1] domain: null,
[1] _events: { finish: [Function: bound resOnFinish] },
[1] _eventsCount: 1,
[1] _maxListeners: undefined,
[1] output: [],
[1] outputEncodings: [],
[1] outputCallbacks: [],
[1] outputSize: 0,
[1] writable: true,
[1] _last: false,
[1] upgrading: false,
[1] chunkedEncoding: false,
[1] shouldKeepAlive: true,
[1] useChunkedEncodingByDefault: true,
[1] sendDate: true,
[1] _removedConnection: false,
[1] _removedContLen: false,
[1] _removedTE: false,
[1] _contentLength: null,
[1] _hasBody: true,
[1] _trailer: '',
[1] finished: true,
[1] _headerSent: true,
[1] socket: null,
[1] connection: null,
[1] _header: 'HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Length: 99\r\nAccess-Control-Allow-Origin: *\r\nSet-Cookie: io=cR5UsvmhPlsVQFwNAAAA; Path=/; HttpOnly\r\nDate: Wed, 10 Apr 2019 01:56:36 GMT\r\nConnection: keep-alive\r\n\r\n',
[1] _onPendingData: [Function: bound updateOutgoingData],
[1] _sent100: false,
[1] _expect_continue: false,
[1] statusMessage: 'OK',
[1] statusCode: 200,
[1] [Symbol(outHeadersKey)]: null },
[1] cleanup: [Function: cleanup],
[1] secret: 'joejeep',
[1] cookies: {},
[1] signedCookies: {},
[1] _parsedUrl:
[1] Url {
[1] protocol: null,
[1] slashes: null,
[1] auth: null,
[1] host: null,
[1] port: null,
[1] hostname: null,
[1] hash: null,
[1] search: '?transport=polling&EIO=3&t=1554861396.1907172',
[1] query: 'transport=polling&EIO=3&t=1554861396.1907172',
[1] pathname: '/socket.io/',
[1] path: '/socket.io/?transport=polling&EIO=3&t=1554861396.1907172',
[1] href: '/socket.io/?transport=polling&EIO=3&t=1554861396.1907172',
[1] _raw: '/socket.io/?transport=polling&EIO=3&t=1554861396.1907172' },
[1] sessionStore:
[1] MemoryStore {
[1] domain: null,
[1] _events:
[1] { disconnect: [Function: ondisconnect],
[1] connect: [Function: onconnect] },
[1] _eventsCount: 2,
[1] _maxListeners: undefined,
[1] sessions:
[1] { 'lPJ4Jj8EI0VqkaPlE17-Fz6F3ipgY7GN': '{"cookie":{"originalMaxAge":1800,"expires":"2019-04-10T01:56:34.019Z","secure":false,"httpOnly":true,"path":"/"},"passport":{"user":"fireyoshiqc"}}' },
[1] generate: [Function] },
[1] sessionID: '4epVaSDpxEGNxjwKZktGJYG0GbSGSvIN',
[1] session:
[1] Session {
[1] cookie:
[1] { path: '/',
[1] _expires: 2019-04-10T01:56:38.004Z,
[1] originalMaxAge: 1800,
[1] httpOnly: true,
[1] secure: false } } }