Abhyudit Jain
Abhyudit Jain

Reputation: 3748

Guard doesn't execute passport startegy in nestJs

I am using nestjs and having an issue with using guards to authenticate a request.

Gist (full code)

import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException, HttpStatus, Logger } from '@nestjs/common';
import { Strategy } from 'passport-localapikey-update';
import { size } from 'lodash';

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

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

    async validate(token: string) {
        Logger.log('HERE!!!!!!!!!!!!!!', 'ApiKeyStrategy');  // Not printed
        const data = await this.authService.authenticateClient(token);
        if (!size(data)) {
            throw new UnauthorizedException('Unauthorized');
        }
        return data;
    }
}

The @UseGuards(AuthGuard('localapikey')) doesn't execute and throws 401 error.

None of the logs are printed.

Upvotes: 1

Views: 1191

Answers (1)

Kim Kern
Kim Kern

Reputation: 60557

You have to pass the validation function in the super constructor of the passport strategy.

constructor(private readonly authService: AuthService) {
  super((token, done) => done(null, this.validate(token)));
}

You can also pass the options object as the first parameter:

constructor(private readonly authService: AuthService) {
  super({apiKeyField: 'myapikeyfield'}, (token, done) => done(null, this.validate(token)));
}

btw: I'd recommend using an instance of Logger instead of accessing it statically, see this thread.

Upvotes: 2

Related Questions