Skip to content

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

@Sanjeevi03

Description

@Sanjeevi03

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions