Different Authorization Levels in HTTP Azure Function | 2023

Authorization levels in Azure Functions determine the level of access required to trigger a function. They are used to secure your functions and control who can invoke them. Azure Functions offer three authorization levels.

  1. Anonymous: No authentication required, accessible by anyone.
  2. Function: Requires a function key to authenticate the caller.
  3. Admin: Reserved for administrative actions, offers higher privileges
Different Authorization Levels in HTTP Azure Function | 2023 1

In this comprehensive article, we will meticulously walk through each access level, delving into their intricacies and discerning the optimal scenarios for their implementation.

Types of Triggers in Microsoft Azure Function

Azure functions are event-based triggered so to execute them we need to have some kind of trigger defined. Here you go the list of triggers supported by the Microsoft Azure function.

  • RabbitMq Trigger
  • Kafka Trigger
  • Kafka Output
  • SignalR
  • Cosmos DB Trigger
  • IoT Hub Trigger
  • Event Grid Trigger
  • Service Bus Topic Trigger
  • Service Bus Queue Trigger
  • Event Hub Trigger
  • SendGrid
  • Time Trigger
  • Blob Trigger
  • HTTP Trigger With Open API
  • Azure Function HTTP Trigger
  • Queue Trigger

In today’s post, we will be focusing mainly on HTTP Trigger binding and will try to explore as much as information we can grab regarding this binding.

Create Using Visual Studio

Visual Studio comes with inbuilt templates to generate the HTTP-triggered-based Azure function.

Select Azure Function Template, Create Azure Function HTTP Trigger
Select Azure Function Template

Select the Azure Function template and Click Next.

Project name and directory information on visual studio,Create Azure Function HTTP Trigger
Project name and directory information on visual studio

Provide the project name and directory information and click on Create project. The next screen will list all the supported binding types on the Azure function.

Select binding types in the azure function,Create Azure Function HTTP Trigger
Select binding types in the azure function

Select the listed options to continue with our demo project.

  • .Net Core 3 as Framework
  • HTTP Trigger as Azure function binding
  • Authorization level as a function
  • Storage Emulator as the storage account

Before we continue with our project, lets understand these options in detail.

Storage Emulator for Development

Azure function required storage to keep the required information while executing each request and maintaining the states and several instances as required, also to distribute the workload and log the information.

Microsoft Storage Emulator is an open-source tool to provide the runtime requirement for Azure functions. So, you don’t have to connect to the actual storage account and bear the cost of Azure infrastructure.

Azure Function Authorization Level

Azure Functions provide different authorization levels to control access and secure your serverless functions. Here are the common authorization levels available in Azure Functions:

  1. Function: This is the default authorization level. It allows anonymous access to the function without requiring any API key or authentication. Anyone with the function URL can invoke the function.
  2. Anonymous: Similar to the Function level, this authorization level allows anonymous access to the function. However, it provides the option to enforce function keys or API keys for additional security. Function keys can be used to control access to individual functions within the function app.
  3. Admin: The Admin authorization level requires a valid Azure Functions key or system key to invoke the function. This level is typically used for administrative tasks and restricts access to trusted users who possess the necessary keys.
  4. User: The User authorization level requires a user-specific authentication token to access the function. It integrates with Azure Active Directory (AAD) or other authentication providers to enforce user-based access control.
  5. System: The System authorization level is reserved for internal system operations and is not intended for general use. It provides elevated privileges and is used by platform-level operations within the Azure Functions runtime.

You can set the authorization level for your Azure Function either at the function level or the function app level, depending on your specific requirements. This allows you to control access and secure your functions based on the desired level of authentication and authorization.

Let’s continue with our demo project

Since the trigger point for the azure function is an HTTP request, there is a need of authorizing it before it starts executing the actual logic implemented under the azure function.

We can navigate to the Authorization enum to find all supported types of authorization.

Authorization level enum in Http Triggered Azure Function
Azure Function Authorization level enum in Http Triggered
Authorization level enum
Authorization level enum
Project structure in visual studio for azure function
Project structure in visual studio for azure function

Once done with the project creation. The structure will look like the above image. There are important files that we need to discuss in detail.

  • host.json
  • local.settings.json

host.json vs local.settings.json file in Azure function

host.json and local.setting.json both files are used for storing the configuration for Azure function.

The key difference between these files is that host.json is used by Azure functions hosted under the Azure portal, on the other hand, local.settings.json is used to keep the configuration of the local environment or while running on a local machine.

Function1 as Http Trigged function

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace HttpTriggered.Demo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string name = req.Query["name"];
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;
            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";
            return new OkObjectResult(responseMessage);
        }
    }
}

So, We have Function1 as the Http Triggered Azure function. Which is configured to allow get and post requests and authorization at the function level.

Also, Function1 has HttpRequest as one of the parameters which will be null in case of getting a request and will have the request body if requested using the post method.

The dependency on ILogger will be resolved automatically, we don’t have to configure anything additional.

But, the Route parameter is null by default. And, can be configured as per the requirements.

Update Route Parameter in the HTTP Triggered Azure Function

Assume, I want to call my function using these route images then we have to just update the route parameter and the complete URL will look like this.

Azure function endpoint
Azure function endpoint

As you can see in the above window /api prefix has been added by default. In case if we want to update that. That can be also done using the host.json file just open the file and paste these lines at the end.

  "extensions": {"http": {"routePrefix": "apiv2"}}

route prefix you can change the name as per the naming convention you follow in your project. After updating the host.json, it should look like this.

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensions": {"http": {"routePrefix": "apiv2"}}
}

And the URL of the function must be changed with a custom route prefix.

Http Trigger Azure Function With Custom Route
Http Trigger Azure Function With Custom Route

Invoke Get using Curl

Let’s execute the azure function get using the curl command in cmd. Pass the default parameter called name and lets wait for the response.

Invoke Http Trigger Azure Function using curl command
Invoke Http Trigger Azure Function using the curl command

Invoke Post Using Postman Client

I assume you have used the Postman app API development. If not go ahead and start learning that. One of the best tools I have ever used for testing is the APIS.

Invoke Http Azure function post method using postman
Invoke Http Azure function post method using Postman

As we see in the above image, we are passing json as the request body in the post method. Which will return the response in the string format.

This is one of the simple requests and responses you can have. However, it can be changed and extended based on the requirement of the individual.

Publish Function Azure Portal

Assuming we have an active Azure subscription. If not go through this article to create one with free credit.

In the left-side navigation bar, you will have the option to create a new resource.

Create Resource Option in Azure Portal
Create Resource Option in Azure Portal

Search for a function app to start creating the function.

Search function app for creating in Azure portal
Search function app for creating in Azure portal

Select the Function App and Click on Create to start creating the function app.

Function App Creation Required fields
Function App Creation Required fields

Provide the required field for creating a function app.

  • Resource group name, Create a new one if does not exist
  • Provide the function name, and keep changing the name until you find the one which is available.
  • Publish option as code, We are not using Docker as of now.
  • Runtime stack, in our demo we are using.Net.
  • The Azure function version, for this demo is 3.1
  • The region, Not all the regions are available if you are using the free subscription of azure.
  • Operating system, you can select anyone .net core is supported in Linux as well in windows environment.
  • In the final step, Click on Review and Create

It might take some time to deploy the function app. Once the app is ready go to the app and download the Publish profile template from the overview section.

Get Publish Profile from Azure function
Get Publish Profile from Azure function

Click on the GetPublish profile link and download the profile. Once you have the downloaded profile.

Go to the visual studio a right-click on the project you will an option from the context menu to publish the project.

Publish profile on azure function
Publish profile on Azure function

Import the downloaded profile for publishing the Azure function. Click on the Import profile option and select the imported file & Click Finish.

Publish using the Import Profile Option in Visual Studio
Publish using the Import Profile Option in Visual Studio
Select Imported profile for publishing the azure function
Select an Imported profile for publishing the Azure function

After completing these steps. You should have a screen like this.

Different Authorization Levels in HTTP Azure Function | 2023 2
Publish profile options

Once we are done with the above stage. It is just a matter of clicking the publish button and the function will be deployed to the Azure portal.

Lets start publishing the project and wait for it. If all goes well then you should receive the success notification else you will have some errors on the console log.

Publish Azure function using visual studio with success
Publish Azure function using visual studio with success

As we see on the screen publishing the Azure function was successful. Now let’s go to the Azure portal and validate the same.

A hosted version of HTTP triggered the azure function
A hosted version of HTTP triggered the azure function

A function is up and running and should be able to take the request and send the response back.

One Function App can hold multiple Azure functions inside it. So to get to our Http triggered function just navigate to the left side pan, there is an option called functions, which can tell you the exact URL and type of authentication accepted by the Azure function.

Azure Functions inside the Function App
Azure Functions inside the Function App

Click on Function1 which is the HttpTriggered azure function. You will have detailed information about the Azure function like URL, authentication, and monitors.

Detailed page of Azure Function
Detailed page of Azure Function

Invoke Function hosted on Azure

Http Triggered functions can be invoked easily by hitting the provided endpoint and passing the function key or host key as a query parameter in the URL.

How to find Azure function URL

Go to the Azure function inside the function app and Click on the GetFunction URL button at the top of the page.

Get Function URL of Http triggered azure function
Get Function URL of Http triggered Azure function

ASA you click on the Get Function Url link. You will have the option to select the function key which will be appended after the function URL. And, Will be used for authentication purposes.

If you remember the initial stage of our Azure function, we have selected the function as AuthorizationLevel. So we can invoke the function using either the host key or the master key. Select the appropriate option in the Get Function Url dropdown and copy the URL.

https://httptriggerdemobeetechnical.azurewebsites.net/apiv2/images?code=rfHaDc0pBoTugnkGUWSIKAUVKTx5KO/KCaj7ZaeYHZZ0xHtd2m6kHQ==

I got the above URL to invoke the HTTP function.

Call Http Trigger Function Using HttpClient

Just copy the above URL on the browser and you should be able to see the response sent by the Azure function.

Call Http triggered azure function get using a browser
Call Http triggered Azure function get using a browser

As we see in the response. We got a successful response from the function.

We can use PostMan my favorite API testing tool to hit the Azure function with a post request.

Post call using postman and HTTP triggered azure function
Post call using Postman and HTTP triggered Azure function

Conclusion

So far we have seen how easy is to create an HTTP trigger Azure function on the local environment using visual studio and how we can take them to the production environment in just one click.

We have covered the following topics in this article.

  • How to Create Http Trigger Function Locally
  • Diffrent types of authorization available for HTTP triggered function
  • Publish Azure function using visual studio and publish profile
  • Invoke Function using host and master key
Scroll to Top