1

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.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Abhyudit Jain
  • 3,640
  • 2
  • 24
  • 32

1 Answers1

2

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.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
  • I noticed that it was working fine when i passed the api key in header under the key 'apiKey'. The localapikey strategy allows to change that by doing "const strat = new LocalApiKeySStrategy(options)". How can I do that here, since PassportStrategy expects the object and not an instance. – Abhyudit Jain Feb 08 '19 at 04:30
  • I've added the answer to your additional question as an edit. – Kim Kern Feb 08 '19 at 09:27
  • I looked through the code of nest.js and the passport-localapikey-update library. I don't think there are docs. :-| – Kim Kern Feb 08 '19 at 10:33