首页 > 解决方案 > 每个域的 Google Oauth2.0 动态 URL

问题描述

我目前正在开发一个应该具有 google Oauth2.0 身份验证的多域网站。我想让它在后端工作。对于每个单独的域,我需要一个包含正确域的重定向 URL。但我似乎无法将自定义反馈 URL 解析为 google OAuth 策略。我知道出于安全原因,谷歌不允许使用动态网址。但我只想要“https://<domain>/googleAuthRedirect?code=<token>”。

我计划解析请求 URL “https://universalBackend/oauth/v2/loginGoogle/<domain>”中的域

我认为应该可以通过在重定向 URL 中使用正确的域为每个请求创建一个自定义策略对象。但我似乎无法弄清楚如何将其放入代码中。

提前致谢。

我当前的passport.js conf

passport.use(
    new GoogleStrategy({
        clientID: '',
        clientSecret: '',
    }, (accessToken, refreshToken, profile, done) => {

        // Todo Check if registered in xfw, if not register, if registered then log in
        console.log('Access', profile.id);
        done();

    })
);

我当前的 authRouter.ts

oAuthRouter.get('/loginGoogle', passport.authenticate('google', {
    scope: ['profile']
}));

oAuthRouter.get('/googleRedirect', passport.authenticate('google'), (req: Request, res: Response) => {
    res.json(req.user)
});

标签: node.jsexpressoauth-2.0google-oauthpassport.js

解决方案


这就是解决方案。这样我可以根据请求动态更改回调 URL。

oAuthRouter.get('/loginGoogle', (req: Request, res: Response, next: NextFunction) => {
    // @ts-ignore
    passport._strategies.google._callbackURL = 'http://localhost:8081/api/OauthV2/googleRedirect';

    // @ts-ignore
    console.log(passport._strategies.google._callbackURL)

    passport.authenticate('google', { scope: ['profile'] })(req, res, next);
});

推荐阅读