使用fastify-session和fastify-webockets时,如何获得对会话的访问?

问题描述

当我在Fastify应用程序中同时使用fastify-websocketfastify-session时,我遇到了问题。

  fastify.get( myWebsocketPath,websocket: true },async (connection,rawRequest) => {

    console.log(`request for websocket connection`)
    if( request.session.authenticated ) {
      myApi( connection.socket )
    }
  })

除了失败之外,因为我只有rawRequest,没有用会话修饰的常规请求。

解决方法

似乎要获取外部句柄,您需要自己设置会话存储。最好使用自定义存储,但是为了简单起见,在本示例中,我将使用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指出正确的方向。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...