当我在我的应用程序中同时使用fastify-websocket和fastify-session时,我遇到了一个问题。
fastify.get( myWebsocketPath, websocket: true },
async (connection, rawRequest) => {
console.log(`request for websocket connection`)
if( request.session.authenticated ) {
myApi( connection.socket )
}
})除非这会失败,因为我只有rawRequest,而不是用会话修饰的常规请求。
发布于 2020-10-24 00:29:29
似乎要为它获取一个外部句柄,您需要自己设置会话存储。最好使用定制存储,但为了简单起见,在本例中我将使用fastify-session提供的内置存储。
let fastifySession = require(`fastify-session`)
let mySessionStore = new fastifySession.MemoryStore /// TODO: customize
let options = { store: mySessionStore, secret: `itsasecrettoeverybody`, cookieName: `sessionId`, expires: 3600000, cookie: { secure: false } }
fastify.register(fastifySession, options)
// ...
const routes = async (fastify, options) => {
fastify.get( myWebsocketPath, websocket: true },
async (connection, rawRequest) => {
/// Retrieve the session
let cookies = rawRequest.headers.cookie.split(`;`)
for( c of cookies ) {
if( c.startsWith(`sessionId=`) ) {
/// Get SessionID from the cookie
let sessionID = c.substring(10).trim()
sessionID = sessionID.substring( 0, sessionID.indexOf(`.`) )
/// Collect session and check the authentication state.
mySessionStore.get( sessionID, ( o, session ) => {
if( session != null && session.authenticated == true ) {
myApi( connection.socket )
}
})
break
}
}
})
}感谢Zekth为我指明了正确的方向。
https://stackoverflow.com/questions/64498762
复制相似问题