繁体   English   中英

"从 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 发出发布请求,以便为用户订阅电子邮件服务,该服务使用我的中间件无法使用的不同身份验证方法。

从第三方 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;

路由器.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);
};

控制器/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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM