首页 > 解决方案 > 如何使用 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);
            });
        }
    });
}));

标签: node.jsexpresspassport.jsdiscorddiscord.js

解决方案


所以我将跳过护照部分,将向您展示令牌交换:

签到方法:

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,他们的文档写得很好:)


推荐阅读