Authenticated REST API with Azure Functions

Summary

If you need to authenticate with Azure AD when using a serverless or a message broker that is acting as the API Gateway the fastest approach is to use Azure’s built-in toolset.

In this post I’ll demonstrate how to Authenticate Azure Functions with Azure AD.

Manage CORS

If you’ve created a new REST web service, when accessing the REST API from a browser, a CORS error will appear similar to the image below.

In order to resolve this error, the Origin ‘http://example.com:8081’ will need to be added to the ‘Allowed Origin’ list.

Note that here you are allowing the requested endpoint to accept requests from the server ‘http://example.com:8081’.

Once this is complete, the CORS error should be resolved.

*Note that you might still receive the CORS error if you have the ‘App Service Authentication‘ set to On. This seems to be a bug, but turning it off and on again seemed to fix it for me.

Add AAD Authentication

Authentication with Azure Active Directory is relatively straight-forward. If you are creating a Function using Visual Studio and C#, ensure that you set the correct authorization level in the HTTP Trigger.

public static HttpResponseMessage (run [HttpTrigger( AuthorizationLevel.Anonymous)]

Under Settings, go to Authentication/Authorization

There are three items to configure here:

  1. Turn on ‘App Service Authentication‘.
  2. Under ‘Action to take when request is not authenticated‘ set the value to: ‘Log in with Azure Active Directory‘.
  3. Under ‘Authentication Providers‘, this setting needs to be configured.

To configure Azure Active Directory, do the following:

  1. Under ‘Management Mode‘ select ‘Express‘.

2. Ensure the button ‘Create New AD App‘ has been selected.

That’s all that is required. After saving the changes – you should see something similar to the screen below.

Test Authentication

When accessing the requested web service endpoint you will notice now that you are required to login.