[英]How to pass request object through Nest.js Guards with Nest.js Passport Module and Passport Discord?
I'm working with nest.js as well as it's passport module and passport-discord to handle discord oauth2 authentication.我正在使用nest.js 以及它的护照模块和护照不和谐来处理discord oauth2 身份验证。
However, I want to pass the request object from my login route through the authentication guard for use later down the line where I check some of the data, and then will want to invoke the logOut()
method on the request object in some situations.但是,我想通过身份验证保护从我的登录路由传递请求 object 以供稍后在我检查一些数据的行中使用,然后在某些情况下需要对请求 object 调用logOut()
方法。
Controller: Controller:
@Get('login')
@UseGuards(DiscordAuthGuard)
login() {
console.log('hello123');
}
Guard:警卫:
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
export class DiscordAuthGuard extends AuthGuard('discord') {
async canActivate(context: ExecutionContext) {
const activate = (await super.canActivate(context)) as boolean;
const request = context.switchToHttp().getRequest();
await super.logIn(request);
return activate;
}
}
Discord Strategy: Discord 策略:
import { Inject } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-discord';
import { IAuthService } from '../interfaces/auth';
export class DiscordStrategy extends PassportStrategy(Strategy) {
constructor(
@Inject('AUTH_SERVICE') private readonly authService: IAuthService,
) {
super({
clientID: 'REDACTED',
clientSecret: 'REDACTED',
callbackURL: 'http://localhost:4000/api/auth/redirect',
scope: ['identify'],
});
}
async validate(accessToken: string, refreshToken: string, profile: Profile) {
console.log('DiscordStrategy Validate Method');
console.log(profile);
// I WANT TO BE ABLE TO GET THE REQUEST OBJECT TO HERE, SO THAT I CAN PASS IT INTO MY AUTH SERVICE
return this.authService.validateUser({ discordId: profile.id });
}
}
Any idea how I would achieve this?知道我将如何实现这一目标吗?
Try passing passReqToCallback
parameter to super in contructor:尝试将passReqToCallback
参数传递给构造函数中的 super:
constructor(
@Inject('AUTH_SERVICE') private readonly authService: IAuthService,
) {
super({
clientID: 'REDACTED',
clientSecret: 'REDACTED',
callbackURL: 'http://localhost:4000/api/auth/redirect',
scope: ['identify'],
passReqToCallback: true,
});
}
and modify the validate function to have signature并修改 validate function 以具有签名
async validate(req: Request, accessToken: string, refreshToken: string, profile: Profile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.