如何使用护照.js使用已登录用户的访问令牌获取 JSON?



我能够执行GET请求以在使用护照提供的访问令牌时从不和谐中获取JSON。如何使用护照获取登录用户的访问令牌以在另一个页面上执行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,他们的文档写得很好:)

最新更新