node.js - 如何使用 passport.js 使用已登录用户的 accessToken 获取 JSON?
问题描述
在使用护照提供的访问令牌时,我可以发出 GET 请求以从不和谐中获取 JSON。如何使用护照获取已登录用户的 accessToken 以在另一个页面上执行 GET 请求?
passport.use(new DiscordStrategy({
clientID: keys.discord.clientID,
clientSecret: keys.discord.clientSecret,
callbackURL: '/auth/discord/redirect'
}, (accessToken, refreshToken, profile, done) => {
request({
url: 'https://discordapp.com/api/users/@me/guilds',
auth: {
'bearer': accessToken
}
}, (err, res) => {
console.log(res.body);
});
User.findOne({ discordId: profile.id }).then((currentUser) => {
if (currentUser) {
done(null, currentUser);
} else {
new User({
discordId: profile.id
}).save().then((newUser) => {
console.log('Created new user: ', newUser);
done(null, newUser);
});
}
});
}));
解决方案
所以我将跳过护照部分,将向您展示令牌交换:
签到方法:
const jwt = require('jsonwebtoken');
[...]
app.post('/signin', passport.authenticate('signin'), (req, res) => {
if (req.user){
// Set the JWT token for this session
const token = jwt.sign(
{ id: req.user.id },
keys.discord.clientSecret,
{ expiresIn: config.SESSION_DURATION } //The validity time (optional)
);
const currentDate = new Date();
return res.status(200).send({
auth: true,
token: token,
// These two properties below are optional if you want to keep track
// of the session duration and send some more user info
tokenDuration: {
expire: currentDate.setMilliseconds(currentDate.getMilliseconds() + config.SESSION_DURATION)},
user: {firstname: req.user.firstname, lastname: req.user.lastname}
});
}
return res.status(401).send('Could not login');
});
然后当您从客户端发出请求时:
axios({
method: 'POST',
url: `${url}/path`,
data: data,
headers: {
'x-access-token': jwtToken, // This is the "token" property from above
},
json: true
})
最后,您在服务器中处理上述请求:
app.post('/path', (req, res) => {
jwt.verify(req.headers['x-access-token'], keys.discord.clientSecret, (err, decoded) => {
if (err) {
// The user is not authorized, handle properly
}
// User is authorized, do stuff
});
希望这足以让您开始。就像我提到的,看看 JWT,他们的文档写得很好:)
推荐阅读
- oracle - 如何在一个表上编写触发器以防止更新数据但将这些数据插入到另一个表中
- reactjs - 是否可以在反应导入中传递道具
- javascript - 再次按下按钮时如何从ul中删除所有li
- java - 查找在多个位置产生常量的所有有效迭代范围
- batch-file - 无法通过批处理文件订阅或发布到我的本地 mosquitto
- javascript - 使用 Django 和 OpenLayers 比较不同的层
- django - 数据未从 Django Rest 检索到 Flutter App
- mysql - 获取Oracle存储过程内表中插入记录的主键值
- ruby-on-rails - 在获取请求时更新属性?
- excel - Powershell 脚本使用管道分隔符和文本限定符将 excel 转换为 csv