Mic*_*elB 5 node.js passport.js passport-google-oauth passport-google-oauth2 nestjs
我正在尝试对我的节点 + 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能进一步调试它以了解为什么/幕后发生了什么?
实际端点:
@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,
});
}
}
Run Code Online (Sandbox Code Playgroud)
我无法使用任何警卫或 UseGuards 装饰器传递选项对象。
我还尝试将额外的对象参数传递给 super 调用,但这也不起作用。
小智 9
塞巴斯蒂安 我也已经处理这个问题大约一周了。我终于找到了问题所在,然后发现有一篇非常相似的 Stack Overflow 文章也有同样的问题:
使用 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
})
);
Run Code Online (Sandbox Code Playgroud)
对于任何使用 Nestjs 并面临同样问题的人,这里是解决方案
class AuthGoogle extends AuthGuard('google') {
constructor() {
super({
prompt: 'select_account'
});
} }
}
// using
@UseGuards(AuthGoogle)
private googleAuth() {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
919 次 |
| 最近记录: |