Microsoft.Identity.Web and Azure Functions (2023)

6 minutes of reading

youwalked recentlyin an interesting situation with authentication. With Serverless and Azure Functions becoming more and more popular, I wanted to see if it was possible to leverage the Microsoft.Identity.Web library within Azure Functions... and it worked!

Originally, my requirement was to support both Azure AD and API static key authentication to the same endpoints. In ASP.NET Core, this is done by simply defining a policy scheme via.AddPolicyScheme, with Azure Functions it's a little different.

Firstly, Azure Functions has no concept of middleware except forFilterit's time to writeadvance, so this is probably not something you want to pursue.

However, Azure Functions supports regularaddiction injection, so you can add your custom services. One of the services is, for example,AddJwtBearerpresented byMicrosoft.AspNetCore.Authentication.JwtBearerPackage. Instead of using playn JwtBearer Middleware, we will useMicrosoft.Identity.Web(MIW). The good thing about MIW is that it simplifies most of the common actions and operations you need to perform. He also makes use ofMicrosoft Chartor callany other APIvery easy!

So to add it you just need to create aStart.csfile that looks like this:

[Mounting: FeaturesHome(Kind of(FunctionsAuthentication.defloration))]namespace FunctionsAuthentication{ Advertising class defloration : FeaturesHome { Advertising to replace Empty To set up(IFunctionsHostBuilder baumeister) { // This is the configuration of environment variables, settings.json, etc. guerra Building = baumeister.get context().Building; authentication(SharedOptions => { SharedOptions.standard scheme = "Conveyor"; SharedOptions.Standard Challenge Scheme = "Conveyor"; }) .AddMicrosoftIdentityWebApi(Building) .EnableTokenAcquisitionToCallDownstreamApi() .AddInMemoryTokenCaches(); } }}

don't forget to addMicrosoft.Identity.Webpack and configure your ownlocal.settings.json(it should probably look like this):

{ "It's encrypted": INCORRECT, "Values": { "AzureWebJobsStorage": "Use development storage = true", "FUNCTIONS_WORKER_RUNTIME": "don't point", "AzureAd: instance": "", „AzureAd:Dominio“: "<your_domain>", "AzureAd: Tenant ID": "<you_that_tenant_of_tenant>", "AzureAd: Client ID": "<client_id>", "AzureAd:ClientSecret": "<client_secret>" }}

Now we have to do a littleHttpContextoExtension, I will explain what it does below:

Advertising static class FunctionsAuthenticationHttpContextExtension{ Advertising static asynchronous assignment<(bool, IActionResult)> AuthenticateFunctionAsync(die HttpContexto httpContexto, line schemaName) { guerra result = suppose httpContexto.AutenticarAsync(schemaName); e (result.Successful) { httpContexto.User name = result.School principal; give back (It's right, Null); } anders { give back (INCORRECT, novo Unauthorized object result(novo Problem Details { title = "Authorization failed.", Detail = result.Failed?.news })); } }}

This extension method is called every time the function is called because regular cannot be used directly[Authorize] as in ASP.NET Core🇧🇷 This extension method does three things:

(Video) Securing Azure Functions with the Microsoft Identity platform

  • Attempts to authenticate principal through provided mediumschemaName
  • If authentication succeeds, it completes.HttpContext.Benutzerwith the most important information as requirements (also authenticatedwork, etc.)
  • If authentication fails, a message will be generated.IActionResultwith the error message (cf.Problem detailsfor more information).

Thanks toHttpContext.Benutzerwith the correct principal, you can also useVerifyUserHasAnyAcceptedScopeto easily validate the range passed in the token.

Next, let's go to the function. First make it a non-static regular class so we can use itITokenAcquisition(will be needed later). Then make sure that the functionpermission levelis set to anonymous ([HttpTrigger(Authorization Level.Anonymous, ...]), otherwise the following issue will occur: Using Azure Functionsmultiple authentication servicesand the permission level turns them on, so you would end up getting errors like schema missing or something.

Then just call themAuthenticateFunctionAsyncwith schema name is defaulttransporter(foraJwtBearerPadrões), but you can replace it with the name of your own policy. The extension method returns atupel, the first value is a boolean, whether the authentication succeeded or not, and the second is what you wantIActionResultwhich it can return if authentication fails.

If you plan to use thesein the name of the riverto get a token for another service with the current user's token (e.g. Microsoft Graph) which you also want to injectITokenAcquisitionin the constructor (this is another reason to fillHttpContext.Benutzergiven thatITokenAcquisitionuses principal for token caching). In the code above, we callAddInMemoryTokenCacheswhich you could argue is inefficient for functions since it's only in memory and not shared. That's right, you can register for a changedistributed token cachein a single line of code (there areImplementations for Redis, SQL, Cosmosytable storage🇧🇷 The rest is as easy as callingGetAccessTokenForUserAsynceITokenAcquisitionand if the scopes are successfully granted, a token will be granted (try calling it again and examine the token to verify that the token cache is working). If you add theMicrosoft ChartYou can easily call the packageGraphServiceClientWhat else.

And now the function code itself:

Advertising class function 1{ Private only reading ITokenAcquisition _tokenAcquisition; Advertising function 1(ITokenAcquisition token acquisition) { _tokenAcquisition = token acquisition; } [function name("function1")] Advertising asynchronous assignment<IActionResult> Run( [Http trigger(authorization level.Anonymous, "to receive", "Mail", rota = Null)] Http request required, data logger Protocol) { guerra (authentication status, AuthenticationResponse) = suppose required.HttpContexto.AuthenticateFunctionAsync("Conveyor"); e (!authentication status) give back AuthenticationResponse; guerra signal = suppose _tokenAcquisition.GetAccessTokenForUserAsync(novo line[] { "" }); Protocol.record information("The C# HTTP trigger function processed a request."); line Name = required.HttpContexto.User authenticated ? required.HttpContexto.User name.identity.Name : Null; line reply to message = null or empty(Name) ? "This HTTP-triggered function was successful. Pass a name in the query string or request body to get a custom response." : $"Hello,{Name}🇧🇷 This HTTP triggered function completed successfully."; give back novo OkObjectResult(reply to message); }}

So far, I've found this to be pretty satisfying, as it doesn't seem to be missing many of the things I'm used to in ASP.NET Core (except attributes). Try and see for yourself!

Also notice that howmentioned christsMIW is not designed to work with resources, so it will likely not receive official support.

Update:Thanks tojennyf19towardConfirmthat the team is interested in the scenario and will help you with any issues you may encounter along the way. just create oneProductionin the repository, if necessary.


Microsoft.Identity.Web and Azure Functions (1)

Alexandre Tuttle

March 19, 2021 at 11:23 am

(Video) Authenticate Azure Function with Azure Web App Using Managed Service Identity

Hi Jan,

Thanks for a great contribution. I have some questions about it:

  1. True, the above currently only works when run locally:

  2. When deploying, should the values ​​in local.settings.json be added to host.json or as app settings for the App Service role?

  3. ...and in general, when I add a NuGet package to an Azure resource like Microsoft.Identity.Web that requires configuration settings, how do I know where to put the configuration values?

I would be very grateful if you can answer.


Alexandre Tuttle

Microsoft.Identity.Web and Azure Functions (2)

Jan Hajek

March 19, 2021 at 2:42 pm

Hi great points:

  1. It also works on Azure (I actually use it in production) but some of the portal integration is lost (e.g. streaming logs) but everything works fine with App Insights.
  2. In this case I use local.settings.json for local development and application settings (environment variables) for Azure hosting.
  3. The configuration is set via Startup.cs during service registration with the service provider (Dependency Injection). The configuration is defined in the Microsoft.Identity.Web documents. For example, the available configuration is shown here:

Microsoft.Identity.Web and Azure Functions (3)

(Video) How to Setup Authentication for Azure Functions

Alexandre Tuttle

March 19, 2021 at 7:54 pm

That was very helpful. Thank you very much for your time and I wish you a nice weekend!

Microsoft.Identity.Web and Azure Functions (4)


May 9, 2021 at 1:02 am

I'm getting the error -Microsoft.AspNetCore.Authentication.Core: No authentication handler registered for schema 'WebJobsAuthLevel'. The registered systems are: B2C. You forgot AddAuthentication().AddSomeAuthHandler?.

Please help..

Microsoft.Identity.Web and Azure Functions (5)

Jan Hajek

May 10, 2021 at 6:31 am

Great point @saurabh. This is a known issue, partially addressed here: To mitigate this error on startup, make sure all your HTTP triggers are set to anonymous level. You could also try: to make other authorization types work as well ( as function key code). You can also use the same code with the in-process hosting model.

Microsoft.Identity.Web and Azure Functions (6)


August 22, 2021 at 4:18 pm.

It does not work. All my HTTP triggers are anonymous level. I am getting errors like below. Until there is a clean solution, I think it's best to place a disclaimer at the top of this post so that future readers don't waste time on this approach.

[2021-08-22T16:13:48.888Z] An unhandled host error occurred. [2021-08-22T16:13:48.893Z] Microsoft.AspNetCore.Authentication.Core: No authentication handler registered for schema 'ArmToken'. The registered systems are: Holder. You forgot AddAuthentication().AddSomeAuthHandler?.

(Video) Authentication for Serverless apps

Microsoft.Identity.Web and Azure Functions (7)


September 12, 2021 at 3:47 am

I have the same error as Kiran. Has anyone successfully implemented a solution like this?

Microsoft.Identity.Web and Azure Functions (8)


July 15, 2022 at 5:11 pm

Thank you for this article, it helped us a lot!

Unfortunately, we encountered an issue related to AddMicrosoftIdentityWebApi, which appears to be a bug:

(Video) Overview of the Microsoft identity platform for developers

leave a comment

Your email address will not be published. Required fields are marked*


Does Azure function support managed identity? ›

Azure Functions provides a managed identity, which is a turn-key solution for securing access to Azure SQL Database and other Azure services. Managed identities make your app more secure by eliminating secrets from your app, such as credentials in the connection strings.

What is Microsoft Identity Web? ›

Microsoft Identity Web is a set of ASP.NET Core libraries that simplifies adding authentication and authorization support to web apps and web APIs integrating with the Microsoft identity platform.

What functions does identity services provide for Microsoft Azure? ›

  • Enable a secure, remote desktop experience from anywhere.
  • Migrate, modernise and innovate on the modern SQL family of cloud databases.
  • Build and scale with managed Kubernetes.
  • Azure PlayFab. ...
  • Execute event-driven serverless code functions with an end-to-end development experience.

What are the disadvantages of Azure Functions? ›

Vendor-lock is the biggest drawback of this function. It is very difficult to run code deployed in Azure function outside the azure environment. The language used in function app such as java, NodeJS, etc are not specialized but the code to establish a connection between resources is specific to azure.

What are the 3 main identity types used in Azure AD? ›

Azure AD manages different types of identities:
  • User. User identity is a representation of something that's Azure AD manages. ...
  • Service principal. A service principal is a secure identity that enables an application or service to access Azure resources. ...
  • Managed identity. ...
  • Device.

How do I authenticate to Azure function? ›

Search for and select the Azure Functions: Open in portal command. Select the subscription and function app name to open the function app in the Azure portal. In the function app that was opened in the portal, locate the Platform features tab, select Authentication/Authorization. Turn On App Service Authentication.

What are the two types of managed identities that are available in Microsoft Azure? ›

Azure manages the identity so you don't have to. There are two types of managed identities: system-assigned and user-assigned. System-assigned managed identities have their lifecycle tied to the resource that created them.

How do I call Azure function with authentication? ›

Enable Azure Active Directory Authentication

Access the newly created Function app from the Azure portal and select "Authentication / Authorization" from the settings menu. Enable App Service Authentication and set the "Action to take when request is not authenticated" to "Log in with Azure Active Directory".

What are the types of Azure functions? ›

There are currently four durable function types in Azure Functions: activity, orchestrator, entity, and client. The rest of this section goes into more details about the types of functions involved in an orchestration.

How does Microsoft identity work? ›

The Microsoft identity platform helps you build applications your users and customers can sign in to using their Microsoft identities or social accounts. It authorizes access to your own APIs or Microsoft APIs like Microsoft Graph.

What is the difference between managed identity and service principal? ›

The key difference between Azure service principals and managed identities is that, with the latter, admins do not have to manage credentials, including passwords. To create a managed identity, go the Azure portal and navigate to the managed identity blade. Then, assign a role to the identity.

Is Microsoft Identity Manager end of life? ›

MIM is now in extended support, and will be so until early 2029. If you have an Azure AD Premium subscription you still get standard support with a few caveats.

What can I use instead of Identity server? ›

Top WSO2 Identity Server Alternatives
  • Okta Single Sign-On.
  • Microsoft Azure Active Directory.
  • PingOne Cloud Platform.
  • ForgeRock Identity Platform.
  • RSA SecurID Access.
  • Oracle Access Management Suite.
  • SecureAuth Arculix.
  • AWS Identity and Access Management (IAM)

Is Microsoft Identity good? ›

Microsoft Identity Manager is a good software that provides the best identity control and helps in the management of employees. It provides the best security solutions and a secured workflow making it simple and more reliable. It gives a much flexible interface and it is easy to use.

Is Azure identity deprecated? ›

Identity grows and as developers continue to migrate existing applications to Azure. Identity, further investment in AppAuthentication will be reduced. Eventually, the library will be deprecated.

Which is not purpose of Azure function? ›

Azure Functions are NOT designed to carry out multiple tasks. The service was designed to perform one thing or as few things in the shortest time possible. Azure Functions is NOT recommended for infrequent, time-sensitive tasks.

Is Microsoft discontinuing Azure? ›

Microsoft is shutting down its Azure Blockchain Service on September 10, 2021. Existing deployments will be supported until that date, but as of May 10 this year, no new deployments or member creation is being supported.

What are the 5 different types of identities? ›

Examples of social identities are race/ethnicity, gender, social class/socioeconomic status, sexual orientation, (dis)abilities, and religion/religious beliefs.

What are the two types of identities? ›

There are two types of identity, that is, social identity and personal identity. Social identity - When an individual tries to establish identity in their respective society, it is termed social identity.

What are the 3 types of identities? ›

Interpersonal identity development is composed of three elements:
  • Categorization: Assigning everyone into categories.
  • Identification: Associating others with certain groups.
  • Comparison: Comparing groups.

How do I call an Azure function from Web API? ›

You can find the documentation for the Microsoft project here.
  1. Deploy the Azure Function App. ...
  2. Deploy the Azure Web App. ...
  3. Create ReactJS App Registration. ...
  4. Create Backend App Registration. ...
  5. Allow ReactJS Web App to Access Backend App API. ...
  6. Function App CORS Configuration. ...
  7. Secure the Function App with Authentication.
30 May 2022

Can I use Azure function as API? ›

Azure API Management supports importing Azure Function Apps as new APIs or appending them to existing APIs. The process automatically generates a host key in the Azure Function App, which is then assigned to a named value in Azure API Management.

How Azure function works internally? ›

Azure Functions is a serverless solution that allows you to write less code, maintain less infrastructure, and save on costs. Instead of worrying about deploying and maintaining servers, the cloud infrastructure provides all the up-to-date resources needed to keep your applications running.

What are the three components of Azure? ›

A wide range of Microsoft's software as a service (SaaS), platform as a service (PaaS) and infrastructure as a service (IaaS) products are hosted on Azure. Azure offers three core areas of functionality; Virtual Machines, cloud services, and app services.

What is Azure function? ›

Azure Functions is a cloud service available on-demand that provides all the continually updated infrastructure and resources needed to run your applications. You focus on the code that matters most to you, in the most productive language for you, and Functions handles the rest.

What are the three types of RBAC controls in Azure? ›

Azure broadly defines three different roles: Reader, Contributor, and Owner. These roles apply to Subscriptions, Resource Groups, and most all Resources on Azure.

Can Azure functions send SMS? ›

The Azure Functions platform will invoke the method, and when it receives the CreateMessageOptions instance, the platform will send the SMS. For the platform to be able to send the SMS, it needs to authenticate with your Twilio account.

How do I use Microsoft Identity Azure AD to authenticate your users? ›

In Overview, select your app's management page. On your app's left menu, select Authentication, and then click Add identity provider. In the Add an identity provider page, select Microsoft as the Identity provider to sign in Microsoft and Azure AD identities.

Can Azure functions send email? ›

The Azure Functions platform will invoke the method, and when it receives the SendGridMessage instance, the platform will send the email. For the platform to be able to send the email, it needs to authenticate with the SendGrid API.

What are the 4 types of function? ›

There are 4 types of functions:
  • Functions with arguments and return values. This function has arguments and returns a value: ...
  • Functions with arguments and without return values. ...
  • Functions without arguments and with return values. ...
  • Functions without arguments and without return values.

What are the 4 different Functions? ›

The types of functions can be broadly classified into four types. Based on Element: One to one Function, many to one function, onto function, one to one and onto function, into function.

What is the difference between Azure Functions and App Service? ›

Azure App Service is a powerful web application hosting platform. Azure Functions, built on top of the App Service infrastructure, enables you to easily build serverless and event-driven compute workloads. Both services are frequently used in multitenant solutions.

When should I use identity server? ›

It can be used to authenticate actual users via sign-in forms and similar user interfaces as well as service-based authentication that typically involves token issuance, verification, and renewal without any user interface. IdentityServer is designed to be a customizable solution.

What three methods are used to verify identity? ›

Many important processes require the applicant to complete identity verification to prove that they are who they claim to be. Methods include facial verification, fingerprint matching, and comparing biometric data from verified sources to the person being checked.

What are the three most common methods used to verify identity? ›

Online identity verification can be performed in a variety of different ways. Common methods include biometric verification (fingerprint or facial recognition), use of one-time password (OTP), digital document verification, or requesting information that only the legitimate user can know.

What is the equivalent of IAM in Azure? ›

Azure Active Directory (AD) is Microsoft's cloud-based identity and access management (IAM) service; it can be used to manage secure user sign-in to thousands of external services, such as Microsoft Office 365, the Azure portal, and other SaaS applications.

How many managed identities are in Azure? ›

There are two types of managed identities: System-assigned. Some Azure resources, such as virtual machines allow you to enable a managed identity directly on the resource.

What is difference between identity management and authentication? ›

Or, identity management is when you authenticate users, and access management is when you authorize users. People often use authentication and authorization interchangeably too, but the truth is that they serve entirely different purposes. Authentication is simply the process of telling 'who' you are.

Which Azure Services Support managed identities? ›

In this article
Service NameDocumentation
Azure Data ExplorerConfigure managed identities for your Azure Data Explorer cluster
Azure Data FactoryManaged identity for Data Factory
Azure Data Lake Storage Gen1Customer-managed keys for Azure Storage encryption
Azure Data ShareRoles and requirements for Azure Data Share
50 more rows
31 Oct 2022

Does AKS support managed identity? ›

An Azure Kubernetes Service (AKS) cluster requires an identity to access Azure resources like load balancers and managed disks. This identity can be either a managed identity or a service principal. By default, when you create an AKS cluster a system-assigned managed identity is automatically created.

What are Azure Functions good for? ›

Azure Functions is a serverless solution that allows you to write less code, maintain less infrastructure, and save on costs. Instead of worrying about deploying and maintaining servers, the cloud infrastructure provides all the up-to-date resources needed to keep your applications running.

Which account types are supported by Microsoft identity platform? ›

The Microsoft identity platform provides support for specific identity types:
  • Work or school accounts when the entity has an account in an Azure Active Directory (AD)
  • Microsoft personal accounts (MSA) for anyone who has account in, Hotmail, Live, Skype, Xbox, etc.
1 Nov 2022

What is the difference between Azure and aks? ›

AKS offers built-in monitoring. Azure Monitor for containers helps you gain visibility into the performance of your clusters. A self-hosted Kubernetes installation, or ACI without Kubernetes, requires a manual installation and configuration of a monitoring solution. Scaling containerized environments can be complex.

How is AKS different from Kubernetes? ›

Kubernetes is the de-facto open source platform for container orchestration but typically requires a lot of overhead in cluster management. AKS helps manage much of the overhead involved, reducing the complexity of deployment and management tasks.

Does AKS use ACI? ›

In such scenarios, you can scale AKS using ACI without the overhead of provisioning additional nodes. ACI is used as a secure extension of AKS, using an implementation of Virtual Kubelet called virtual nodes. This enables AKS to deploy pods on demand to ACI in a secure, logical environment, isolated from other users.

How many types of Azure functions are there? ›

There are currently four durable function types in Azure Functions: activity, orchestrator, entity, and client. The rest of this section goes into more details about the types of functions involved in an orchestration.

Does Azure have 2 factor authentication? ›

MFA works in Azure Active Directory by requiring two or more of the following authentication methods: A password. A trusted device that's not easily duplicated, like a phone or hardware key. Biometrics like a fingerprint or face scan.

What is the difference between Web API and Azure function? ›

Azure Functions are always static methods

Actions of Web API, with the aid of using the way, don't have the static modifier. This outcome in a good-sized architectural extrude at some stage in the migration, specifically with dependency injection (DI).

What is the difference between Azure functions and WebJobs? ›

Summary. Azure Functions offers more developer productivity than Azure App Service WebJobs does. It also offers more options for programming languages, development environments, Azure service integration, and pricing. For most scenarios, it's the best choice.

What is the difference between function app and web app? ›

If your web applications use Web APIs as middleware to bunch of data and business logic related tasks. Unlike Web API or services, Azure Functions are not designed to multiple tasks. An Azure functions app should be designed to do one task only.


1. Azure Functions for the IT Pro
(John Savill's Technical Training)
2. On .NET Live - Securing Web APIs with Microsoft.Identity.Web
3. Authenticate Azure Function App using Azure AD
4. What is MSAL + Microsoft.Identity.Web?
5. Identity and secure resource access in App Service and Azure Functions : Build 2018
(Microsoft Developer)
6. How to protect APIs using the Microsoft identity platform
(Microsoft Azure)


Top Articles
Latest Posts
Article information

Author: Golda Nolan II

Last Updated: 10/05/2023

Views: 5700

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.