Nest: Using global auth guard doesn't work

Created on 11 May 2018  路  9Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[] Bug report
[ ] Feature request
[x] Documentation issue or request
[] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

  const app: INestApplication & INestFastifyApplication = await NestFactory.create(AppModule, new FastifyAdapter(), {
    logger: new AppLogger('root')
  });
  app.setGlobalPrefix('v3');
  app.useGlobalGuards(AuthGuard('jwt'));
  await app.listen(4200);

This allows anyone to access my routes. However when I decorate my routes with the UseGuards decorator it works as intended:

  @Get('profile/:tag')
  @UseGuards(AuthGuard('jwt'))
  public getProfile(@Param() params: { tag: string }): {} {
    return this.xService.getProfile(params.tag);
  }

Expected behavior

  app.useGlobalGuards(AuthGuard('jwt'));

I expected this to protect my whole app just as it worked with the decorated route.

Environment


Nest version: 5.0.0.-rc4 & "@nestjs/passport": "^1.0.10",

For Tooling issues:

  • Node version: 8.x
  • Platform: Windows
3rd-party 馃殌 question 馃檶

Most helpful comment

Let's try:

app.useGlobalGuards(new (AuthGuard('jwt')));

All 9 comments

Let's try:

app.useGlobalGuards(new (AuthGuard('jwt')));

@kamilmysliwiec That does actually work, can you explain why this is needed / what it does?

Prettier actually formats it to

app.useGlobalGuards(new (AuthGuard('jwt'))());

AuthGuard is a function that returns mixin class, and thus we have to create an instance by ourselves (useGlobalGuards() doesn't accept types). The reason why it returns a class is that we could leave the instantiation responsibility to Nest, and therefore Nest can reuse a single instance across multiple contexts.

Thanks for the explanation. Since your suggestion seems to work, I'll close this issue then.

Glad it helped :)

What is the best/nest.js way to add route exceptions, so that anonymous routes can also be implemented?

+1 interested in an answer for the previous comment.

What is the best/nest.js way to add route exceptions, so that anonymous routes can also be implemented?

Check a suggestion here: #964

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

artaommahe picture artaommahe  路  3Comments

hackboy picture hackboy  路  3Comments

anyx picture anyx  路  3Comments

breitsmiley picture breitsmiley  路  3Comments

cojack picture cojack  路  3Comments