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!
The
validatefunction does not run at all when:the token is not set in the request
the token is not valid
the token expired
the token is encrypted but no
secretOrKeyis 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
secretOrKeyproperty in the constructor of yourLocalStrategyclass and give it the same string value you encrypt your tokens with when you create them