Azure 函数 Javascript 调用通过 HTTP 触发器挂钩使用

问题描述 投票:0回答:1

为了保护 API,函数可以从 HTTP 请求中检索承载令牌。 因为我想对多个函数执行相同的操作,所以我想我可以在

preInvocation
钩子中实现它。但是,挂钩无法访问该请求。 我真的想知道调用钩子的用例是什么。

我希望找到类似ExpressJS中间件的东西。

谢谢

javascript azure-functions
1个回答
0
投票

您说得对,Azure Functions 目前不提供可直接访问 HTTP 请求的预调用挂钩。但是,还有其他方法可以跨多个功能实现基于令牌的身份验证:

1。功能级认证(简单案例):

如果您的身份验证逻辑相对简单,不需要复杂的重用,您可以直接在每个函数中集成令牌检索和验证:.

module.exports = async function (context, req) {
  const token = req.headers.authorization?.split(' ')[1]; // Extract token from Authorization header

  if (!token) {
    context.res = {
      status: 401, // Unauthorized
      body: 'Missing or invalid authorization token'
    };
    return;
  }

  // Validate token (replace with your actual validation logic)
  const isValid = validateToken(token); // Replace with a function that returns true/false

  if (!isValid) {
    context.res = {
      status: 401, // Unauthorized
    };
    return;
  }

  // Access protected resources here
  // ...

  context.res = {
    body: 'Success! (Protected resource accessed)'
  };
};

// Sample token validation function (replace with your actual logic)
function validateToken(token) {
  // Simulate token validation
  return token === 'secret-token'; // Replace with actual token validation
}

这种方法可以保持代码本地化,但对于复杂的场景来说可能不是最容易维护的。

2。共享身份验证模块(推荐用于可重用性):

为了可重用且更易于维护的身份验证逻辑,请创建一个单独的模块来处理令牌验证:

const jwt = require('jsonwebtoken'); // Install using npm install jsonwebtoken

// Authentication module (replace with your actual token validation logic)
const auth = {
  validateToken: (token) => {
    try {
      const decoded = jwt.verify(token, 'your-secret-key'); // Replace with your secret key
      return decoded.userId !== undefined; // Check for a valid user identifier
    } catch (error) {
      return false;
    }
  }
};

module.exports = async function (context, req) {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token || !auth.validateToken(token)) {
    context.res = {
      status: 401, // Unauthorized
      body: 'Missing or invalid authorization token'
    };
    return;
  }

  // Access protected resources here
  // ...

  context.res = {
    body: 'Success! (Protected resource accessed)'
  };
};
  • auth
    模块导入到您的函数文件中并利用其
    validateToken
    方法。
  • 这种方法提高了代码的可重用性并简化了跨多个功能的身份验证逻辑。

调用挂钩的用例(虽然对于令牌检索来说并不理想):

虽然不适合请求对象访问,但 Azure Functions (Node.js) 中的调用挂钩还有其他有价值的用例:

  • 集中日志记录:实现预调用挂钩来记录所有函数共有的详细信息,例如函数名称、调用 ID 和时间戳。
  • 指标跟踪:使用预调用挂钩捕获所有函数的自定义指标,从而深入了解总体函数使用情况。
  • 预处理数据:对于特定场景,您可以使用预调用挂钩来执行跨函数常见的初步数据转换或验证。

如果您需要使用 Azure Functions 进行更高级的身份验证,请探索与 Azure Active Directory (AAD) 集成以进行集中授权和管理。

© www.soinside.com 2019 - 2024. All rights reserved.