gpt4 book ai didi

javascript - 如何同时发送对象和使用 Passport 进行身份验证

转载 作者:行者123 更新时间:2023-11-30 20:00:56 24 4
gpt4 key购买 nike

尽管这个问题看起来很模糊,但我需要一种方法来发送 json 对象并同时使用 Passport 进行身份验证。该对象是 req.isAuthenticated ,稍后将在前端作为检查点使用 axios 进行拾取。这就是我的意图。到目前为止,使用下面的代码,对象将不会被发送。

app.get('/login',
passport.authenticate('saml', {
successRedirect: '/assert',
failureRedirect: '/',
}),
(req, res) => {
res.json({isAuthenticated: req.isAuthenticated()})
}
);

最佳答案

这是我项目中的示例示例:

authorizeLocal: (req, res, next) => {
passport.authenticate('local-auth', (err, user, info) => {
if (info) console.log(info);
if (err) return next(err);
if (!user) return res.status(200).send({failReason: 'wrong login/password'});
req.logIn(user, err => {
if (err) return next(err);
delete user.password;
req.session.cookie.maxAge = 24 * 60 * 60 * 1000; // 24 hours
if (user.role === 'operator') {
user.status = 'Online';
operatorsService.setStatus('Online', user.id)
.then(result => {
dialogsService.getWaitingDialogs();
user.work_time = result;
res.status(200).send(user);
})
.catch(() => res.status(200).send({failReason: 'Service error'}));
} else res.status(200).send(user);
});
})(req, res, next);
},

在那里您可以看到 passport req.logIn,它(需要 local-auth 策略或其他在您的情况下)执行身份验证,如果成功则触发回调逻辑。您可以更深入地拥有任何用户/对象获取/生成逻辑。例如,我离开了我的案子。 OperatorsService.setStatus 返回一些时间数据,这些数据存储给用户(用户在策略逻辑运行后作为回调参数获取)并作为响应发送。您可以在此处添加 user.isAuthenticated = req.isAuthenticated();

所以你会有这样的东西:

auth.route.js

app.get('/login', authCtrl.authorizeLocal);

authCtrl.js

authorizeLocal: (req, res, next) => {
passport.authenticate('saml', (err, user, info) => {
if (info) console.log(info);
if (err) return next(err);
// if (!user) return res.status(200).send({failReason: 'wrong login/password'});
req.logIn(user, err => {
if (err) return next(err);
res.status(200).send({isAuthenticated: req.isAuthenticated()}));
});
})(req, res, next);
},

关于javascript - 如何同时发送对象和使用 Passport 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com