【问题标题】:Fetch secret from Vault when initializing next.js初始化 next.js 时从 Vault 获取密钥
【发布时间】:2020-12-31 06:10:53
【问题描述】:

我将 next.js 与库 https://github.com/auth0/nextjs-auth0/ 一起使用

要初始化该库,我需要使用 async/await 从 Vault 中获取一个秘密,但我得到了 Promise { <pending> }

我原以为以下方法会起作用:

// utils/auth0.js

import { initAuth0 } from '@auth0/nextjs-auth0';
const vault = require('./vault');

async function getSecretFromVault() {
  const res = await vault.fetchSecret();
  console.log(res);  // shows my secret correctly
  return res;
}

const secret = getSecretFromVault();
console.log(secret);  // shows Promise { <pending> }

export default initAuth0({
  clientId: "my_ID",
  clientSecret: secret  // this will be invalid: UI shows "client_id is required"
  ....
});

这样做的正确方法是什么?

【问题讨论】:

    标签: next.js auth0 hashicorp-vault


    【解决方案1】:

    async 方法返回 promise,您应该使用 await 来获取异步数据。

    由于模块导出是 sync,最好导出一个 async 方法,该方法将调用 Vault 并返回 Auth0 的初始化。

    // utils/auth0.js
    
    import { initAuth0 } from '@auth0/nextjs-auth0';
    const vault = require('./vault');
    
    async function getSecretFromVault() {
      const res = await vault.fetchSecret();
      console.log(res); // shows my secret correctly
      return res;
    }
    
    let instance;
    
    async function getAuth0() {
      if(instance) {
        return Promise.resolve(instance);
      }
      
      const secret = await getSecretFromVault();
      // -------------^
      instance = initAuth0({
        clientId: 'my_ID',
        clientSecret: secret, // this will be invalid: UI shows "client_id is required"
      });
      
      return instance;
    }
    
    export default getAuth0;
    
    // usage
    
    import getAuth0 from './utils/auth0';
    
    export default async function login(req, res) {
      const auth0 = await getAuth0();
      // --------------------^ get instance
      try {
        await auth0.handleLogin(req, res);
      } catch (error) {
        console.error(error);
        res.status(error.status || 400).end(error.message);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 2012-04-28
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多