graphql icon indicating copy to clipboard operation
graphql copied to clipboard

Missing Details/Unexpected behaviour Authenticating over Websocket using graphql-ws.

Open Efosaok opened this issue 5 years ago • 7 comments

Bug Report

The section of the documentation on authentication over websocket says that the data returned from forRoot.subscriptions.['subscription-transport-ws' || 'graphql-ws'].onConnect callback will be acessible in the forRoot.context callback via connection.context. However that doesn't seem to be the case at least for graphql-ws. connection is undefined in context regardless of what is returned from onConnect.

Irrespective of what was returned from forRoot.subscriptions.[graphql-ws'].onConnect, I was only able to access the connectionParams parsed from the client via context directly like this

{
  context: ({ connectionParams, connection }) => { } // connection will evaluate to undefined while connectionParams hold necessary authentication parameters. 
}

I am not sure if this is the intended behaviour and was missed out on the documentation or a bug but I am sure someone else will experience this soon enough.

Efosaok avatar Sep 18 '21 11:09 Efosaok

Hi @Efosaok, if you find some time, create a minimal reproduction of a clonable git repository so that the NestJS core team can evaluate the problem you reported.

However, try to propose this issue on the discord support channel as well.

Tony133 avatar Sep 18 '21 14:09 Tony133

Please provide a minimum reproduction repository.

kamilmysliwiec avatar Sep 27 '21 09:09 kamilmysliwiec

I'll create one today. my apologies I have had no time really.

Efosaok avatar Sep 27 '21 12:09 Efosaok

I am seeing a similar issue, but for subscriptions-transport-ws configuration. It actually appears that the context method is not being called for subscriptions, even after the initial onConnect ack.

I've verified that the onConnect is called once at the beginning, and the correct { user } payload is being returned; but the context method is never called.

This may be an issue with how I've set up the gql module, so i will include my config below:

    const config = GraphQLModule.forRootAsync({
      imports: [ConfigModule, AuthModule, UsersModule],
      inject: [ConfigService, UsersService, 'TOKEN_VERIFIER'],
      useFactory: (
        configService: ConfigService,
        usersService: UsersService,
        tokenVerifier: any
      ) => {
        const authorize = async (accessToken: string) => {
          const token = await tokenVerifier.verify(accessToken);
          return usersService.userFromToken(token);
        };

        return {
          autoSchemaFile: path.join(process.cwd(), 'src/schema.gql'),
          sortSchema: true,
          cors: true,
          installSubscriptionHandlers: true,
          playground: false,
          plugins: [ApolloServerPluginLandingPageLocalDefault()],
          subscriptions: {
            'subscriptions-transport-ws': {
              path: '/subscriptions',
              onConnect: async (connectionParams: any) => {
                if (typeof connectionParams?.accessToken !== 'string') {
                  return false;
                }

                const user = await authorize(connectionParams?.accessToken);
                return { user };
              },
            },
            'graphql-ws': {
              path: '/subscriptions',
              onConnect: async ({ connectionParams }) => {
                if (typeof connectionParams?.accessToken !== 'string') {
                  return false;
                }

                const user = await authorize(connectionParams?.accessToken);
                return { user };
              },
            },
          },
          context: ({ connection, req, res }) => {
            // Only called after standard queries and mutations, not subscription connects
            return connection
              ? {
                  req: {
                    ...req,
                    ...connection.context,
                  },
                  res: res,
                }
              : { req: req, res: res };
          },
        };
      },
    });

chrismllr avatar Oct 14 '21 17:10 chrismllr

I believe I was able to resolve the issue:

On this line within subscriptions-transport-ws: https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/server.ts#L316

The result of the onConnect cb is merged with the context for subsequent messages, and in my case, my current-user decorator was accessing context.req.user, so my change was simple:

// From
const user = await authorize(connectionParams?.accessToken);
return { user };

// To
const user = await authorize(connectionParams?.accessToken);
return { req: { user } };

That said, the context method is still never called for subscriptions, which is OK, because the subscriptions-transport-ws lib is doing this merge you. But this might be worth updating in the documentation, if it is indeed the case.

chrismllr avatar Oct 14 '21 17:10 chrismllr

I also have this issue. No time to make a full repo for this at the moment, but its really simple. Stock set-up, have an onConnect return any value - that value is not available in context whatsoever.

zacksinclair avatar Oct 22 '21 19:10 zacksinclair

I believe I was able to resolve the issue:

On this line within subscriptions-transport-ws: https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/server.ts#L316

The result of the onConnect cb is merged with the context for subsequent messages, and in my case, my current-user decorator was accessing context.req.user, so my change was simple:

// From
const user = await authorize(connectionParams?.accessToken);
return { user };

// To
const user = await authorize(connectionParams?.accessToken);
return { req: { user } };

That said, the context method is still never called for subscriptions, which is OK, because the subscriptions-transport-ws lib is doing this merge you. But this might be worth updating in the documentation, if it is indeed the case.

Yes this worked for me as well. @kamilmysliwiec FYI

SakisTsalk avatar Jun 27 '22 09:06 SakisTsalk