eic*_*han 6 oauth node.js express vue.js passport.js
我对如何在我的应用程序中管理 OAuth 流程感到有些困惑。我可以让它工作,但我不确定最佳实践,并希望找到一些关于该主题的好文章/教程/文档。
我的应用程序结构如下:
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);
}
}
)
);
Run Code Online (Sandbox Code Playgroud)
这些是我的登录组件中的身份验证方法:
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
});
}
}
Run Code Online (Sandbox Code Playgroud)
我的困惑来自这样一个事实,即为了启动 OAuth 流程,我需要通过链接到 /api/login/google 来实际离开我的 Vue 应用程序,这会重定向到 Google OAuth 页面。OAuth 完成后,我不会重定向到我的 Vue 应用程序,而是重定向到 Node 后端(通过 Passport 配置中的回调设置)。
使其工作的一种方法是在弹出窗口中打开该 OAuth 流,通过我的 Vue 应用程序跟踪该窗口的内容,一旦我获得用户对象,我就关闭窗口并在前端登录用户. 但不知何故,这似乎不太正确。
我应该找到一种方法让回调函数真正重定向到我的 Vue 应用程序并让 Vue 应用程序处理它吗?任何带有示例的在线资源可以清楚地理解它?
谢谢你的帮助!
小智 3
:) 你好,
对于单页 Web 应用程序,您应该使用授权代码流,并且在尝试 oauth 后使用 Passport,您应该有一个中间件,可以在失败或成功时重定向您:Passport 文档:
对我来说,一个很好的例子是这个Traversy Media - 带有 oAuth 的后端应用程序
我不认为护照是问题,令牌的流动在你的情况下......
| 归档时间: |
|
| 查看次数: |
367 次 |
| 最近记录: |