Javascript 如何判断用户何时登录| Express | Passport |节点
我为自己构建了一个express后端API(端口3000)和一个Vue.js前端端口(8080)。我在后端服务器上实现了passport身份验证登录系统。如果我转到localhost:3000/auth/google,登录系统就会工作,我会在我的mongoose数据库中获得一个google ID 我的服务器上有这段代码,成功登录后会重定向到我的前端,但我现在如何知道用户已登录到我的Vue.js前端Javascript 如何判断用户何时登录| Express | Passport |节点,javascript,node.js,express,authentication,passport.js,Javascript,Node.js,Express,Authentication,Passport.js,我为自己构建了一个express后端API(端口3000)和一个Vue.js前端端口(8080)。我在后端服务器上实现了passport身份验证登录系统。如果我转到localhost:3000/auth/google,登录系统就会工作,我会在我的mongoose数据库中获得一个google ID 我的服务器上有这段代码,成功登录后会重定向到我的前端,但我现在如何知道用户已登录到我的Vue.js前端 app.get( '/auth/google', passport.authenticat
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.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);
});
}
)
);
};````
在受保护的路由内,您应该能够在req.User字段中看到用户:
app.get('/protectedURL',
passport.authenticate('google'),
function(req, res) {
res.json(req.user);
});
如果用户未登录,/protectedURL调用将返回401错误。您可以生成一个
jsonwebtoken
,并在响应
对象的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')
,但如何从前端实现这一点?我必须重定向到另一个端口?我想我遗漏了什么…你为什么要重定向到另一个端口?如果要连接到其他服务器,则该服务器需要使用相同的passport设置并连接到相同的会话信息。用户信息存储在会话中,您需要使用相同的passport设置才能从会话中反序列化用户。因为I Vue在8080上自动启动了它,所以我对此没有太多考虑。如果我使用相同的端口,会更容易吗?看看在Vue中使用,这样前端/后端就不需要知道它们是独立的服务器:module.exports={devServer:{proxy:'http://localhost:4000{}
非常好,正是我所需要的。我已经收到了,但如何解密呢this.data=this.$cookies.get('token');var decoded=jwt.verify(this.data,'18331831')代码>不工作?例如,在中间件功能的后端对其进行解码