繁体   English   中英

如何在 Node-Express / Vue Web 应用程序中管理 OAuth?

[英]How to manage OAuth in Node-Express / Vue web app?

我对如何在我的应用程序中管理 OAuth 流程感到有些困惑。 我可以让它工作,但我不确定最佳实践,并希望找到一些关于该主题的好文章/教程/文档。

我的应用程序结构如下:

  • 一个 Vue 前端,通过 axios 向后端发出 HTTP 请求
  • 使用 Passport.js 的 Node.js / Express 后端,允许本地、谷歌和 Facebook 策略

Passport 是这样配置的:

passport.use(
    new GoogleStrategy(
        {
            clientID: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
            callbackURL: '/api/login/google/callback'
        },
        async (accesToken, refreshToken, profile, done) => {
            try {
                let user = await User.findOne({ googleId: profile.id });
                if (user) {
                    if (
                        user.email != profile.emails[0].value ||
                        user.pic != profile.photos[0].value
                    ) {
                        user.email = profile.emails[0].value;
                        user.pic = profile.photos[0].value;
                        user.save();
                    }
                    return done(null, user);
                } else {
                    user = await User.findOne({
                        email: profile.emails[0].value
                    });
                    if (user) done(new UserError('existing-user'));
                    const newUser = await new User({
                        googleId: profile.id,
                        email: profile.emails[0].value,
                        name: profile.displayName,
                        pic: profile.photos[0].value
                    }).save();
                    return done(null, newUser);
                }
            } catch (e) {
                return done(e);
            }
        }
    )
);

这些是我的登录组件中的身份验证方法:

methods: {
        async login() {
            await authClient.login(this.credentials);
        },
        async googleLogin() {
            window.open('/api/login/google', 'loginPopup', 'menubar=on');
            // window.location.href = '/api/login/google';
        },
        async facebookLogin() {
            window.location.href = '/api/login/facebook';
        },
        async requestResetToken() {
            await userClient.requestResetToken({
                email: this.emailReset
            });
        }
    }

我的困惑来自这样一个事实,即为了启动 OAuth 流程,我需要通过链接到 /api/login/google 来实际离开我的 Vue 应用程序,该应用程序重定向到 Google OAuth 页面。 OAuth 完成后,我不会重定向到我的 Vue 应用程序,而是重定向到 Node 后端(通过 Passport 配置中的回调设置)。

使其工作的一种方法是在弹出窗口中打开该 OAuth 流,通过我的 Vue 应用程序跟踪该窗口的内容,一旦我获得用户对象,我就关闭窗口并在前端登录用户. 但不知何故,这似乎不太正确。

我应该找到一种方法让回调函数真正重定向到我的 Vue 应用程序并让 Vue 应用程序处理它吗? 任何带有示例的在线资源可以清楚地理解它?

谢谢你的帮助!

:) 你好,

对于单页 Web 应用程序,您应该在 oauth 尝试后使用授权代码流和 Passport,您应该有一个中间件,可以在失败或成功的情况下重定向您: Passport 文档

在此处输入图片说明

对我来说一个很好的例子是这个Traversy Media - 带有 oAuth 的后端应用程序

我不认为护照是问题,令牌的流量在你的情况下......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM