#graphql-ws auhentication missing

6 messages · Page 1 of 1 (latest)

surreal ferry
#

https://docs.nestjs.com/graphql/subscriptions
According to documentation this must be correct on the issue which says “Cannot read properties of undefined (reading 'authorization')”
I see the logged user data from below console.log however getting error like above. I tried with different type of authorization none of them really worked. #1025199348096700476

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { PrismaService } from './prisma.service';
import { BigintScalar } from './dts/big-int.scalar';
import { Context } from 'graphql-ws';
import * as jwt from 'jsonwebtoken';

@Module({
  providers: [PrismaService],
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      subscriptions: {
        'graphql-ws': {
          path: '/subscriptions',
          onConnect: (context: Context<any>) => {
            const { connectionParams } = context;
            const authToken = connectionParams?.Authorization;
            console.log(connectionParams);
            if (authToken) {
              const token = authToken.split(' ')[1];
              const decoded = jwt.verify(
                token,
                process.env.JWT_SECRET || 'default_secret',
              );

              (context.extra as any).user = decoded;
            }
          },
        },
      },
      context: (context: any) => {
        if (context?.extra?.request) {
          return {
            req: {
              ...context?.extra?.request,
              headers: {
                ...context?.extra?.request?.headers,
                ...context?.connectionParams,
              },
            },
          };
        }

        return { req: context?.req };
      },
      autoSchemaFile: 'schema.gql',
      playground: true,
      definitions: {
        customScalarTypeMapping: {
          BigInt: 'bigint',
        },
      },
      resolvers: { bigint: BigintScalar },
    }),
  ],
})
export class AppModule {}
{
  "dependencies": {
    "@apollo/server": "^4.9.3",
    "@nestjs/apollo": "^12.0.9",
    "@nestjs/common": "^10.0.0",
    "@nestjs/core": "^10.0.0",
    "@nestjs/graphql": "^12.0.9",
    "@nestjs/jwt": "^10.1.1",
    "@nestjs/mapped-types": "*",
    "@nestjs/passport": "^10.0.2",
    "@nestjs/platform-express": "^10.0.0",
    "@prisma/client": "^5.3.0",
    "@types/passport-jwt": "^3.0.9",
    "bcrypt": "^5.1.1",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "firebase-admin": "^11.11.0",
    "graphql": "^16.8.0",
    "graphql-subscriptions": "^2.0.0",
    "graphql-upload": "^13.0.0",
    "graphql-ws": "^5.14.2",
    "jsonwebtoken": "^9.0.2",
    "passport": "^0.6.0",
    "passport-facebook": "^3.0.0",
    "passport-google-oauth20": "^2.0.0",
    "passport-jwt": "^4.0.1",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.8.1"
  },
  "devDependencies": {
    "@nestjs/cli": "^10.0.0",
    "@nestjs/schematics": "^10.0.0",
    "@nestjs/testing": "^10.0.0",
    "@types/bcrypt": "^5.0.0",
    "@types/express": "^4.17.17",
    "@types/graphql": "^14.5.0",
    "@types/graphql-upload": "^8.0.11",
    "@types/jest": "^29.5.2",
    "@types/node": "^20.3.1",
    "@types/passport-google-oauth20": "^2.0.12",
    "@types/supertest": "^2.0.12",
    "@typescript-eslint/eslint-plugin": "^5.59.11",
    "@typescript-eslint/parser": "^5.59.11",
    "eslint": "^8.42.0",
    "eslint-config-prettier": "^8.8.0",
    "eslint-plugin-prettier": "^4.2.1",
    "jest": "^29.5.0",
    "prettier": "^2.8.8",
    "prisma": "^5.3.0",
    "source-map-support": "^0.5.21",
    "supertest": "^6.3.3",
    "ts-jest": "^29.1.0",
    "ts-loader": "^9.4.3",
    "ts-node": "^10.9.1",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.1.3"
  },
}```
quick gardenBOT
#

Please format your question or answer with Markdown formatting.
It leads to better readability and an easier time to spot problems.
For code blocks, you can wrap your block with three back ticks before and after the block, and after the first three back ticks you can add a language (like ts) to add syntax highlighting.
e.g.

```ts
@Injectable()
export class MySuperAwesomeService {
constructor(@Inject('InjectionToken') private readonly dep: SomeDependency) {}

getRandomNumber(): number {
return Math.round(Math.random() * 1000);
}
}
```

Becomes :point_down:

@Injectable()
export class MySuperAwesomeService {
  constructor(@Inject('InjectionToken') private readonly dep: SomeDependency) {}

  getRandomNumber(): number {
    return Math.round(Math.random() * 1000);
  }
}
surreal ferry
#

Bumb

steep leaf
#

Anything else in the error like a stack trace? Are you certain that connectionParams is in the context and has an Authorization property? Also, that error looks like it may point at a different part of the code

surreal ferry
#

I updated my app module now it not crashes but still getting authentication error like this

Connection connected
{
Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1NSIsInVpZCI6InY2aTN2cVB3UTFNTEo0V1NzaE1BdU10ZDVFRDMiLCJpYXQiOjE2OTk4MTEzNDcsImV4cCI6MTcwMjQwMzM0N30.rkKaq5eyMWwnm4OOoxwjhwjBxt7zlMrrVdcCpTMDIBc'
 }
Connection disconnected

// Response received at 04:07:24
{
  "errors": [
    {
      "message": "Unauthorized",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "messageSent"
      ]
    }
  ]
}```
#

My mobile auth strategy I am logging the param it always late for subscription like this

 Connection connected
Connection disconnected
{
 userId: '1',
 uid: 'vxasd123142dsadasd',
 iat: 1699811347,
 exp: 1702403347
}