【问题标题】:Manage passportjs Google-Strategy in a Vue App在 Vue 应用程序中管理 passportjs Google-Strategy
【发布时间】:2020-12-27 02:11:20
【问题描述】:

我想将 passportjs 的 Google 策略集成到我的 Vue 应用程序中(Node 在后端运行)。

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

上运行

我设置了这样的本地策略(正在运行):

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

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

这是我的代码:

google-strategy-route.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>

有人有想法吗?

谢谢!

【问题讨论】:

    标签: node.js vue.js oauth-2.0 passport.js passport-google-oauth


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-10
      • 2020-09-08
      • 1970-01-01
      • 2017-03-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多