我想在我的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>
有人有想法吗?
谢谢 !