Secure an azure function http trigger with passport azure-ad

Viewed 675

How can I protect azure function using the passport and passport-azure-ad I don't want to protect all of the azure functions, some functions will require an access_token to be validated before running the code. And most of the samples i found online are using express, which cannot be used in azure functions.

I tried the below approach but the code still ran without authentication.

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",
    };
  }
};
2 Answers

Since Azure functions are not managed by you (you only provide the code), the authentication happens in another place and can be configured via the portal.
If only some of the functions are required to be protected, your best call would be to divide the functions into two different function apps. One would be protected and one won't.

Here is the official documentation for authentication: https://docs.microsoft.com/en-us/azure/app-service/overview-authentication-authorization


From what I saw, the authentication is not enabled when using Linux as the operating system, so your deployment must be on Windows OR you could use Azure API Management.

I have an example that creates an Azure function with authentication in the portal. The code itself is written in .Net but the configuration in the portal should be exactly the same.
https://www.pshul.com/2020/02/07/azure-ad-authentication-from-angular-to-azure-functions/

Related