Nest: Can't throw http error inside Guard

Created on 5 Apr 2019  路  3Comments  路  Source: nestjs/nest

I'm submitting a...


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

Current behavior


I've created a custom auth session guard. If the validation fails, I send an unauthorized exception to user using throw new UnauthorizedException('invalid_access_token'). I can see that the response is correct:

{
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid_access_token"
}

But in nestApp console:

Unhandled Promise rejection: invalid_access_token ; Zone: ; Task: Promise.then ; Value: { Error: invalid_access_token
at SessionAuthGuard. (/Users/fpachecoibz/Projects/fpachecoibz/dist/server.js:740:35)
at step (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:133:27)
at Object.next (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:114:57)
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:107:75
at new ZoneAwarePromise (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/zone.js/dist/zone-node.js:910:29)
at Object.__awaiter (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:103:16)
at SessionAuthGuard.canActivate (/Users/fpachecoibz/Projects/fpachecoibz/dist/server.js:730:63)
at GuardsConsumer.tryActivate (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/guards/guards-consumer.js:13:34)
at canActivateFn (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/router/router-execution-context.js:116:59)
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/router/router-execution-context.js:40:37
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/router/router-proxy.js:8:23
at Layer.handle [as handle_request] (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/layer.js:95:5)
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/index.js:281:22
response:
{ statusCode: 401,
error: 'Unauthorized',
message: 'invalid_access_token' },
status: 401,
message: 'invalid_access_token' } Error: invalid_access_token
at SessionAuthGuard. (/Users/fpachecoibz/Projects/fpachecoibz/dist/server.js:740:35)
at step (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:133:27)
at Object.next (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:114:57)
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:107:75
at new ZoneAwarePromise (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/zone.js/dist/zone-node.js:910:29)
at Object.__awaiter (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/tslib/tslib.js:103:16)
at SessionAuthGuard.canActivate (/Users/fpachecoibz/Projects/fpachecoibz/dist/server.js:730:63)
at GuardsConsumer.tryActivate (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/guards/guards-consumer.js:13:34)
at canActivateFn (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/router/router-execution-context.js:116:59)
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/router/router-execution-context.js:40:37
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/@nestjs/core/router/router-proxy.js:8:23
at Layer.handle [as handle_request] (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/layer.js:95:5)
at /Users/fpachecoibz/Projects/fpachecoibz/node_modules/express/lib/router/index.js:281:22

Expected behavior


I need the correct response (It's ok) but without errors in nest app console.

Minimal reproduction of the problem with instructions

This is my current code:

// NestJS
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { HttpArgumentsHost } from '@nestjs/common/interfaces';
import { JwtService } from '@nestjs/jwt';

// Express
import * as express from 'express';

// Services
import { AuthService } from './../services/auth.service';

// Interfaces
import { AdminInterface } from './../../admin/interfaces/admin.interface';
import { JwtPayloadInterfae } from './../interfaces/jwt-payload.interface';

@Injectable()
export class SessionAuthGuard implements CanActivate {

  /**
   * constructor
   * 
   * @param authService auth service
   * @param jwtService nestjs jwt service
   */
  constructor(
    private readonly authService: AuthService,
    private readonly jwtService: JwtService
  ) { }

  /**
   * canActivate
   * 
   * @param executionContext nestjs execution context
   * @returns if can access to route or no
   */
  public async canActivate(executionContext: ExecutionContext): Promise<boolean> {

    const httpArgumentsHost: HttpArgumentsHost = executionContext.switchToHttp();

    const request: express.Request = httpArgumentsHost.getRequest();

    const accessToken: string = request.session.access_token;

    if (!accessToken || !accessToken.length || !this.jwtService.verify(accessToken)) {

      delete request.session.access_token;

      throw new UnauthorizedException('invalid_access_token');

    }

    const admin: AdminInterface = await this.authService
      .validate(this.jwtService.decode(accessToken) as JwtPayloadInterfae);

    if (!admin) {

      delete request.session.access_token;

      throw new UnauthorizedException('invalid_access_token');

    }

    (request as any).admin = admin;

    return true;

  }

}

What is the motivation / use case for changing the behavior?


I'm building an Angular Universal + NestJS site, and I need session or cookie auth

Environment


@nestjs/common: ^6.0.4
@nestjs/core: ^6.0.4
@nestjs/jwt: ^6.0.0
@nestjs/mongoose: ^6.0.0
@nestjs/ng-universal: ^0.5.0
@nestjs/platform-express: ^6.0.4
@nestjs/swagger: ^3.0.2



For Tooling issues:
- Node version: 11.13.0  
- Platform:  Mac 

Most helpful comment

Hi again,

Is not a question, is a bug because in guards documentation (https://docs.nestjs.com/guards) I can read that for send other kind of http exception, just throw that exception.

For example, throw new exception('invalid_access_token'). But the console shows me an error: Unhandled Promise rejection: invalid_access_token

All 3 comments

Please, use StackOverflow for such questions.

Hi again,

Is not a question, is a bug because in guards documentation (https://docs.nestjs.com/guards) I can read that for send other kind of http exception, just throw that exception.

For example, throw new exception('invalid_access_token'). But the console shows me an error: Unhandled Promise rejection: invalid_access_token

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

janckerchen picture janckerchen  路  3Comments

menme95 picture menme95  路  3Comments

tronginc picture tronginc  路  3Comments

KamGor picture KamGor  路  3Comments

marshall007 picture marshall007  路  3Comments