passport strategy is not invoking while using passport-oauth2 in nestjs

358 Views Asked by At

auth.controller.ts:

import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '@nestjs/passport';
import { Request, Response } from 'express';
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}
  @Get()
  @UseGuards(AuthGuard('oauth2'))
  async login() {
    return 'hello world'
  }
  @Get('callback')
  @UseGuards(AuthGuard('oauth2'))
  callback(@Req() req:Request, @Res() res: Response) {
    res.redirect('/');
  }
}

strategy.ts:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy,VerifyCallback } from 'passport-oauth2'
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy,'oauth2') {
  constructor() {
    super({
      authorizationURL: 'www.example.com/login/connect/authorize',
      tokenURL: 'www.example.com/login/connect/token',
      clientID: 'client-id',
      clientSecret: 'client-secret',
      callbackURL: 'callback-url',
      passReqToCallback: true
    });
  }
async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
  var user = {
    accessToken: accessToken,
    refreshToken: refreshToken,
    profile: profile
  };
  console.log(user);
  return done(null, user);
 }
}

strategy.ts is not invoking and not logging the user variable.

I tried to authenticate the user using passport-oauth2 package in nestjs.The problem is, strategy is not calling and not returning the user's accessToken.My expectation is strategy.ts file should return the accessToken and user.
And I'm not sure UseGuards(AuthGuard('oauth2')) is working. Any solutions please!

1

There are 1 best solutions below

0
Ahmed Sbai On

The validate function does not run at all when:

  1. the token is not set in the request

  2. the token is not valid

  3. the token expired

  4. the token is encrypted but no secretOrKey is provided:

here in your example, the part when you create the token is missing so if you are using a secret key to encrypt the token you have to specify a secretOrKey property in the constructor of your LocalStrategy class and give it the same string value you encrypt your tokens with when you create them