Google Oauth2 登录后将 JWT 传递到 UI 应用程序

问题描述 投票:0回答:2

我创建了一个具有单独后端和前端的 MERN 应用程序。我使用

passport-google-oauth20
npm 包添加了对 Google Oauth2 登录的支持。

所以我在后端暴露了一个端点,如下:

class AccountAPIs {
    constructor() { }

    redirectToSuccess(req, res) {
        const accountServiceInst = AccountService.getInst();
        let account = req.session.passport.user;
        let filePath = path.join(__dirname + '../../../public/views/loginSuccess.html');
        let jwt = accountServiceInst.generateJWT(account);
        // how do I send this jwt to ui application
        res.sendFile(filePath);
    }

    loadMappings() {
        return {
            '/api/auth': {
                '/google': {
                    get: {
                        callbacks: [
                            passport.authenticate('google', { scope: ['profile', 'email'] })
                        ]
                    },
                    '/callback': {
                        get: {
                            callbacks: [
                                passport.authenticate('google', { failureRedirect: '/api/auth/google/failed' }),
                                this.redirectToSuccess
                            ]
                        }
                    },
                    '/success': {
                        get: {
                            callbacks: [this.successfulLogin]
                        }
                    }
                }
            }
        };
    }
}

以下是护照设置供参考:

let verifyCallback = (accessToken, refreshToken, profile, done) => {
    const accountServiceInst = AccountService.getInst();
    return accountServiceInst.findOrCreate(profile)
        .then(account => {
            return done(null, account);
        })
        .catch(err => {
            return done(err);
        });
};

let googleStrategyInst = new GoogleStrategy({
    clientID: serverConfig.auth.google.clientId,
    clientSecret: serverConfig.auth.google.clientSecret,
    callbackURL: 'http://localhost/api/auth/google/callback'
}, verifyCallback);

passport.use(googleStrategyInst);

在 UI 应用程序中,单击按钮时,我将打开一个新窗口,该窗口将打开 '/api/auth/google' 后端 API。使用 google 帐户进行身份验证后,窗口会重定向到 '/api/auth/google/callback' 后端 API,我可以在其中生成 JWT。我不确定如何将此 JWT 传输到前端应用程序,因为它是在单独的窗口中打开的。

我知道

res.cookie('jwt', jwt)
是一种方法。请在这里建议最佳实践..

node.js reactjs jwt handshake passport-google-oauth2
2个回答
0
投票

有两种方法将令牌传递给客户端:

1-正如您所提到的,您将令牌放入 cookie 中

2-您将重定向URL中的令牌作为参数“CLIENT_URL/login/token”传递给客户端,以便您可以在前端客户端中提取令牌


0
投票

我也被这个问题困扰了,你找到解决办法了吗?

© www.soinside.com 2019 - 2024. All rights reserved.