首页 > 解决方案 > 使用护照 azure-ad 保护 azure 函数 http 触发器

问题描述

如何使用 保护 azure 函数passport并且passport-azure-ad我不想保护所有 azure 函数,某些函数需要在运行代码之前验证 access_token。而且我在网上找到的大多数示例都是使用 express 的,不能在 azure 函数中使用。

我尝试了以下方法,但代码仍然在没有身份验证的情况下运行。

const passport = require("passport");
const config = require("../shared/config");
const createMongoClient = require("../shared/mongo");
const BearerStrategy = require("passport-azure-ad").BearerStrategy;

const bearerStrategy = new BearerStrategy(config, function (token, done) {
  // Send user info using the second argument
  done(null, {}, token);
});
passport.use(bearerStrategy);
passport.initialize();

module.exports = async function (context, req) {
  passport.authenticate("oauth-bearer", { session: false });
  const dish = req.body || {};

  if (dish) {
    context.res = {
      status: 400,
      body: "Dish data is required! ",
    };
  }

  const { db, connection } = await createMongoClient();

  const Dishes = db.collection("dishes");

  try {
    const dishes = await Dishes.insertOne(dish);
    connection.close();

    context.res = {
      status: 201,
      body: dishes.ops[0],
    };
  } catch (error) {
    context.res = {
      status: 500,
      body: "Error creating a new Dish",
    };
  }
};

标签: azure-functionspassport.js

解决方案


由于 Azure 功能不是由您管理(您只需提供代码),因此身份验证发生在另一个地方,并且可以通过门户进行配置。
如果只需要保护部分功能,最好将这些功能分成两个不同的功能应用程序。一个会受到保护,一个不会。

这是认证的官方文档:https ://docs.microsoft.com/en-us/azure/app-service/overview-authentication-authorization


据我所见,使用 Linux 作为操作系统时未启用身份验证,因此您的部署必须在 Windows 上,或者您可以使用Azure API Management

我有一个在门户中创建带有身份验证的 Azure 函数的示例。代码本身是用 .Net 编写的,但门户中的配置应该完全相同。
https://www.pshul.com/2020/02/07/azure-ad-authentication-from-angular-to-azure-functions/


推荐阅读