0

我想在我的Vue应用程序中集成passportjs的谷歌策略(节点在后端运行)。

Vue 应用程序在localhost:8080上运行,Node 在localhost:5000上运行

我设置了一个本地策略(正在工作),如下所示:

  • axios.post 从 Vue App 到认证路由
  • 检查并验证我的路由中的用户/护照,并将 JWT 令牌发送到 Vue 应用程序
  • 将令牌存储在本地存储中

我想为 Google 策略做同样的事情,但由于重定向,我无法发送令牌。

这是我的代码:

谷歌策略路由.js

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

router.get(
    '/google/callback',
    passport.authenticate('google', {
        failureRedirect: '/',
        session: false,
    }),
    (req, res) => {
        const payload = {
            user: {
                id: req.user._id,
            },
        };
        jwt.sign(payload, process.env.jwtSecret, (err, token) => {
            if (err) throw err;
            res.json({ token });
        });
    }
);

google-strategy-auth.js

passport.use(
        new GoogleStrategy(
            {
                clientID: process.env.GOOGLE_CLIENT_ID,
                clientSecret: process.env.GOOGLE_CLIENT_SECRET,
                callbackURL: 'http://localhost:5000/api/auth/google/callback',
                passReqToCallback: true,
                proxy: true,
            },
            async function (request, accessToken, refreshToken, profile, done) {
                try {
                    const existingUser = await User.findOne({ email: profile.email });
                    if (existingUser) {
                        return done(null, existingUser);
                    }
                } catch (err) {
                    console.log(err);
                }
                try {
                    done(null, newUser);
                } catch (err) {
                    console.log(err);
                }
            }
        )
    );

在 Vue 应用程序中,我有一个指向 /api/auth/google 的 href

<a href="/api/auth/google">Connexion Google</a>

有人有想法吗?

谢谢 !

4

1 回答 1

0

最后,我决定不使用passportjs。由于它是 Node 中间件,因此使用令牌进行重定向非常复杂。我使用 Javascript SDK 集成连接弹出窗口,当用户登录时,我在后面检查前面发送的令牌的值并获取用户信息。后面的签到由 Google 的 Auth Library 管理:https ://github.com/googleapis/google-auth-library-nodejs

希望这个答案会对某人有所帮助!

于 2020-09-11T14:13:41.787 回答