【问题标题】:How to implement refresh token flow with Passport.js on Node.js backend?如何在 Node.js 后端使用 Passport.js 实现刷新令牌流?
【发布时间】:2021-12-24 00:24:30
【问题描述】:

正如标题所说的那样;我想知道如何在 Passport.js 中实现令牌的检索。

目前我实施了以下策略:

passport.use(new GoogleStrategy({
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: '/api/auth/google/callback'
    },
    async (accessToken, refreshToken, profile, done) => {
        const newUser = {
            googleId: profile.id,
            displayName: profile.displayName,
            firstName: profile.name.givenName,
            lastName: profile.name.familyName,
            image: profile.photos[0].value,
            email: profile.emails[0].value
        };

        try {
            let user = await User.findOne({ googleId: profile.id });
            if(user) {
                done(null, user);
            } else {
                user = await User.create(newUser);
                await Key.create({
                    googleId: user.googleId,
                    keyProvider: 'Google',
                    token: accessToken,
                    refreshToken: refreshToken
                });
                done(null, user);
            }
        } catch (err) {
            console.error(err);   
        }
    }));

现在,例如,我想调用 Google API,让我们说这条路线:

router.get('/list', async (req, res) => {
   console.log('list called');

   const result = await axios({
       method: "GET",
       headers: {
           'Authorization': "Bearer [token which is stored in my db]",
       },
       "Content-Type": "application/json",
       url: 'https://www.googleapis.com/youtube/v3/subscriptions?channelId=[someid]',
   });
   console.log(result);
});

我将在哪里以及如何实现一个函数/中间件/模块,每次我向 Google API 发出请求时都会调用它,它会在出错时检索新的 accessToken,然后重试调用?

由于我对 Node.js/Express 还很陌生,我不知道如何将这样的流程放入代码中。我知道要实现的唯一选择是使用 axios 捕获错误,然后在每个 Google API 端点中手动检索带有冗余代码的新 accessToken。

【问题讨论】:

    标签: node.js google-api passport.js access-token refresh-token


    【解决方案1】:

    我想说这里有两个主要概念:

    设计模式

    正如您所说,使用新的访问令牌重试 401 是标准的 - 这里有一些 axios code of mine

    AXIOS 规格

    Axios 有interceptorshere is an example that does 401 retries 的概念。

    个人偏好

    两者都可以——我更喜欢我的方法,它曾经被称为service agent 模式。重要的因素是:

    • 使调用 API 的业务逻辑代码简洁明了
    • 请记住,可能还需要处理其他跨领域问题,因此也要为此腾出空间

    【讨论】:

    • 这正是我想要的,谢谢 Gary!
    猜你喜欢
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 2021-07-11
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多