在执行 Google OAuth 流程时,可以传递加密状态 (base64),该状态将作为参数传递给最终回调。例如,当您想要将用户重定向到特定页面时,这非常有用。 (https://developers.google.com/identity/protocols/oauth2/web-server)
是否可以将 OAuth 状态与 Nest.js 身份验证库一起使用?似乎状态参数被忽略了,我在文档中找不到任何内容。
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(readonly configService: ConfigService) {
super({
clientID: configService.get('google.clientId'),
clientSecret: configService.get('google.clientSecret'),
callbackURL: `${configService.get('apiUri')}${configService.get('google.callbackUrl')}`,
passReqToCallback: true,
scope: ['profile', 'email'],
});
}
}
为了解决这个问题,我向设置状态值的类添加了一个
authenticate
函数。
authenticate(req, options) {
options.state = 'your state value here'
super.authenticate(req, options)
}
免责声明:我试图实现与您所描述的类似的目标,并且这种方法对我有用,但我不确定这是否是处理此问题的“正确”方法。
@Injectable()
export class GoogleAuthGuard extends AuthGuard('google') {
getAuthenticateOptions(context: ExecutionContext) {
// you can get access to the request object.
// const request = this.getRequest(context);
return {
state: `my-custom-state_${Date.now()}`,
};
}
}
并且在您的
auth.controller
中,您可以通过查询值访问此 state
参数。
@UseGuards(GoogleAuthGuard)
@Get('google/callback')
async googleCallback(@Query('state') state: string): Promise<string> {
console.log({ state });
return state;
}