我为自己构建了一个快速后端 API(端口 3000)和端口(8080)上的 Vue.js 前端,我在后端服务器上实现了 Passport 身份验证登录系统。如果我访问 localhost:3000/auth/google,登录系统就会正常工作,并且我会在我的 mongoose 数据库中获得一个 google-ID。
我的服务器上有这段代码,成功登录后会重定向到我的前端,但我现在如何知道用户已登录我的 Vue.js 前端?
app.get(
'/auth/google',
passport.authenticate('google', {
scope: ['profile']
})
);
app.get(
'/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('http://localhost:8080/profile');
}
);
我的 Passport 配置是这样设置的
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((id, done) => {
User.findById(id, function(err, user) {
done(err, user);
});
});
module.exports = function(passport, GoogleStrategy) {
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/google/callback'
},
function(token, tokenSecret, profile, done) {
var query = { googleId: profile.id };
var update = {
$set: {
googleId: profile.id
}
};
var options = { new: true, upsert: true };
User.findOneAndUpdate(query, update, options, function(err, u) {
return done(err, u);
});
}
)
);
};````
最佳答案
您可以生成一个jsonwebtoken
并将其设置在response
对象的cookie中
app.get(
'/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
let token = jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
user: req.user //if you have user here
}, 'secret');
res.cookie("token", token, {httpOnly:false})
res.redirect('http://localhost:8080/profile');
}
);
在 Vue 中,您可以使用像 vue-cookies
这样的包来获取 cookie $cookies.get('token')
关于javascript - 如何判断用户何时登录 | express | Passport | Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860930/