passport-oauth2 icon indicating copy to clipboard operation
passport-oauth2 copied to clipboard

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

Open Sanjeevi03 opened this issue 2 years ago • 2 comments

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. passport authentication is working perfectly in express.js but not in nest.js

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: 'url/callback',
      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);
 }
}

And I'm not sure UseGuards(AuthGuard('oauth2')) is working. Any solution or ideas please!

Sanjeevi03 avatar Jul 19 '23 06:07 Sanjeevi03

Is your strategy LocalStrategy defined as a provider in your auth module ?

RochMoreau avatar Aug 02 '23 08:08 RochMoreau