我正在尝试对我的 Node + nestjs api 中的用户进行身份验证,并希望提示用户选择一个帐户。
如果您只登录了 1 个帐户,则不会显示提示,即使您使用 2 个帐户登录并收到提示,重定向中的 URL 的参数中仍然包含 &prompt=none。
事实上,我可以确认提示选项没有区别。
我的代码简化如下:
import { OAuth2Strategy } from "passport-google-oauth";
import { PassportStrategy } from "@nestjs/passport";
@Injectable()
export class GoogleStrategy extends PassportStrategy(OAuth2Strategy, "google") {
constructor(secretsService: SecretsService) {
super({
clientID: secretsService.get("google", "clientid"),
clientSecret: secretsService.get("google", "clientsecret"),
callbackURL: "https://localhost:3000/auth/google/redirect",
scope: ["email", "profile", "openid"],
passReqToCallback: true,
prompt: "select_account",
});
}
async validate(req: Request, accessToken, refreshToken, profile, done) {
const { name, emails, photos } = profile;
const user = {
email: emails[0].value,
firstName: name.givenName,
lastName: name.familyName,
picture: photos[0].value,
accessToken,
};
return done(null, user);
}
}
我怎样才能进一步调试它以了解为什么/幕后发生了什么?
实际端点:
@Controller("auth")
export class AuthController {
@Get("google")
@UseGuards(AuthGuard("google"))
private googleAuth() {}
@Get("google/redirect")
@UseGuards(AuthGuard("google"))
googleAuthRedirect(@Req() req: Request, @Res() res: Response) {
if (!req.user) {
return res.send("No user from google");
}
return res.send({
message: "User information from google",
user: req.user,
});
}
}
我无法使用任何 guard 或 UseGuards 装饰器传递选项对象。
我还尝试将额外的对象参数传递给 super 调用,但这也不起作用。
最佳答案
塞巴斯蒂安 我也一直在处理这个问题大约一个星期。我终于找到了问题所在,然后发现有一篇非常相似的Stack Overflow文章也有同样的问题:
Auto login while using passport-google-oauth20
初始化时出现问题 OAuth2Strategy
带有选项的类。它不会将它的选项传递给 passport.authenticate(passport, name, options, callback)
打电话自 passport.authenticate(...)
仅在为路由注册中间件处理程序时调用。
因此您需要通过 prompt: 'select_account'
当您注册时 passport.authenticate()
路由中间件
像这样:
router.get(
'/auth/google',
passport.authenticate('google', {
accessType: 'offline',
callbackURL: callbackUrl,
includeGrantedScopes: true,
scope: ['profile', 'email'],
prompt: 'select_account', // <=== Add your prompt setting here
})
);
关于node.js - 仅登录 1 个谷歌帐户时,Passport Google Oauth2 不提示选择帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62268243/