Next.js Discord

Discord Forum

Pass a JWT to a nest.js API graphQL Query

Unanswered
Purple Martin posted this in #help-forum
Open in Discord
Purple MartinOP
I'd like to setup a simple auth guard on a nest.js API.

I'm using next-auth to handle authentication in my client. Using the logs, I can see that an access token is properly attached to my session. I'm using https://www.apollographql.com/blog/announcement/frontend/using-apollo-client-with-next-js-13-releasing-an-official-library-to-support-the-app-router/ to create the query client, and pass the authorization token through the context option. Again, the log shows that I have a properly formatted token

But the auth guard raises an error, saying that the token is malformed. Here is the guard:

    @Injectable()
    export class AuthGuard {
      constructor(private jwtService: JwtService) {}
    
      async canActivate(context: ExecutionContext) {
        const ctx = GqlExecutionContext.create(context);
    
        const request = ctx.getContext().req;
        const secret = process.env.NEXTAUTH_SECRET;
    
        if (request.headers.authorization) {
          try {
            const token = request.headers.authorization.replace('Bearer ', '');
    
            if (!token) {
              throw new UnauthorizedException();
            }
    
            console.log({ secret, token });
            const payload = await this.jwtService.verifyAsync(token, {
              secret,
            }); // this raises the error
            console.log('payload', payload);
          } catch (error) {
            console.log('error', error);
            throw new UnauthorizedException();
          }
        }
        return false;
      }
    }

The logs show that the server has both the token and the secret.

Did I miss something? I made sure that the JWT secret is the same for client and server. The only thing I'm not sure of is the format of my token (it looks like this: Bearer lX4YWhSDZipTMY67luQXJpZU5dWxlp (I changed some characters, but it seems a bit short to me)

2 Replies

did you typo 2 times or are you using nest.js
Purple MartinOP
I'm using both next.js and nest.js 🙂