从 Node Express 应用程序向需要自己的身份验证的第三方 api 发出请求的最佳方式是什么?

What is the best way to make a request from a node express app to a third party api that requires its own authentication?

我有一个 node express 应用程序,它使用 keycloak 身份验证来保护所有 API 端点。已设置 Express 中间件进行身份验证,以确保来自前端的每个传入请求都具有适当的 keycloak 令牌。我需要从我的节点应用程序向第三方后端 API 发出 post 请求,让用户订阅使用我的中间件无法使用的不同身份验证方法的电子邮件服务。

从第三方提出请求的最佳做法是什么 API?我正在考虑 创建一个新的 express 实例并使用一个单独的中间件特定于 post 请求 。这是一件好事还是有更好的方法?

这是我的节点应用程序的简化版本。见

index.js

import { authmware } from "./authmware";
import express from "express";
import { router } from "./router";

const app = express();
authmware(app);
router(app);

app.use((err, req, res, next) => {
  logger.error(err.message);
  const code = err.code ? err.code : 500;
  const message = err.message ? err.message : "Internal Server Error";

  res.status(code).json({ error: message, success: false });
});

export default app;

router.js

import express from "express";
import createProfile from "../../controllers/createProfile";
    
const router = express.Router();
    
router.post("/", createProfile);
    
export const router = (app) => {
   app.use("/api/v1/createProfile", router);
};

controllers/createProfile.js

const createProfile = async (req, res) => {

  // ... Do some stuff

  // ** make request to a different api here ** 
  await makeThirdPartyApiRequest();

}

我如何让这个第三方 api 请求使用不同的身份验证方式?

这是一个非常常见的用例。您可以在您的节点服务器中使用 10 个第三方 API,并且无论您用于客户端请求的身份验证如何,它们都具有不同的身份验证机制。

await makeThirdPartyApiRequest();
  // http request to API
  // attach proper auth headers (API key / jwt / basic auth / oAuth token). This will be based on the authentication method the API is offering.
}

根据您最近的评论更新:

API 应该有一些关于如何使用用户密钥和秘密密钥进行身份验证的文档。例如:Google APIs 只要求您发送 API 密钥并请求 https://cloud.google.com/api-keys/docs/overview