【发布时间】: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