#Error "[AuthGuard] undefined"

1 messages · Page 1 of 1 (latest)

thorn laurel
#

I'm trying to figure out where the console message [AuthGuard] undefined comes from, what is best best way to find where its coming from?

Console when executing request with the invalid bearer token:

[Nest] 26200  - 02/04/2023, 2:48:46 PM     LOG [NestApplication] Nest application successfully started +16ms
[Nest] 26200  - 02/04/2023, 2:48:49 PM   ERROR [AuthGuard] a2
[Nest] 26200  - 02/04/2023, 2:48:49 PM   ERROR [AuthGuard] undefined

My guard:

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class AuthTokenGuard extends AuthGuard('authToken') {}

My strategy:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { Strategy } from 'passport';
import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthTokenStrategy extends PassportStrategy(Strategy, 'authToken') {
  constructor(private readonly authService: AuthService) {
    super();
  }

  /**
   * Authenticates a requiest with an auth token from the authorization header.
   */
  async authenticate(request: Request): Promise<void> {
    const authorization = request.headers.authorization;

    if (!authorization) {
      return this.fail('No authorization header provided.');
    }

    const [scheme, token] = authorization.split(' ', 2);

    if (!scheme || scheme.toLowerCase() !== 'bearer') {
      return this.fail('a1');
    }

    if (!token || token.length !== 64) {
      return this.fail('a2');
    }

    try {
      const authToken = await this.authService.verifyToken(token);
      return this.success(authToken);
    } catch {
      return this.fail('a3');
    }
  }
}
hazy igloo
#

Make sure you use it in the controllers

thorn laurel
#

I have it in my controller

import { Body, Controller, Get, Patch, UseGuards } from '@nestjs/common';
import { UserId } from '../../auth/decorators/user-id.decorator';
import { AuthTokenGuard } from '../../auth/guards/auth-token.guard';
import { MeResponseDto } from '../dtos/me-response.dto';
import { UpdateMeBodyDto } from '../dtos/update-me-body.dto';
import { UsersService } from '../services/users.service';

@Controller('internal/users')
@UseGuards(AuthTokenGuard)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get('me')
  async me(@UserId() userId: string): Promise<MeResponseDto> {
    const user = await this.usersService.findById(userId);

    return {
      id: user.id,
      name: user.name,
    };
  }

  // ...
}