Security Frameworks
How to Implement OAuth 2.0 Framework for Securing APIs
Implementing OAuth 2.0 to secure your ASP.NET Core Web API with Microsoft Entra ID requires a clear, stepwise setup. It involves preparing your development environment with the .NET 9 SDK, registering your API app and exposing OAuth scopes in the Entra tenant, then configuring your API project for authentication and authorization.
This guide walks you through each essential step to enforce token-based security while maintaining manageable developer usability.

Quick answer
Start by installing the .NET 9 SDK and ensuring access to a Microsoft Entra tenant where you'll register your API application. Register your API in the Entra portal, record its client and tenant IDs, and expose a scope such as access_as_user to define permissions.
Use the command dotnet new webapi --auth SingleOrg --name MyWebApi to scaffold an API project preconfigured for Azure AD authentication. Configure your appsettings.json with tenant ID, client ID, and scopes.
Add the Microsoft.Identity.Web package and invoke AddMicrosoftIdentityWebApiAuthentication to integrate OAuth 2.0 middleware. In your request pipeline, use app.UseAuthentication() before app.UseAuthorization().
Protect your API endpoints by applying [Authorize] and [RequiredScope] attributes to enforce token and scope validation. Finally, run your API with dotnet run and verify it accepts only valid tokens with the correct scopes, rejecting unauthorized requests.
Step-by-step guide
Prerequisites for OAuth 2.0 API Protection with Microsoft Entra ID
Before diving into implementing OAuth 2.0 to secure your ASP.NET Core Web API using Microsoft Entra ID, it's important to prepare your environment and resources properly. First, ensure you have the .NET 9 SDK installed on your development machine; this is essential for creating and running the API project.
Next, you'll need access to a Microsoft Entra tenant—this acts as your identity provider where your applications and permissions are managed. Within this tenant, you'll register your API application, which is a crucial step to enable OAuth 2.0 authorization flows.
This registration process involves setting up identifiers and exposing scopes that define what client applications can access.
Having your Microsoft Entra tenant and API app registration ready ensures you'll be able to configure your ASP.NET Core project effectively and enforce security controls using OAuth 2.0. Without these prerequisites, the integration will not function as expected, so I recommend verifying these components first before proceeding to the implementation steps.
Sources: Quickstart: Protect an ASP.NET Core Web API.
Register the API Application in Microsoft Entra ID
To register your API application in Microsoft Entra ID, start by logging into the Microsoft Entra admin portal. Navigate to the ‘App registrations’ section and select ‘New registration’ to create a new application.
Give your API app a descriptive name and specify the supported account types, typically within your organization’s tenant if it's for internal use. After the app is created, locate its Application (client) ID and Directory (tenant) ID; you'll need these for configuration.
Next, expose an API scope by going to the ‘Expose an API’ tab. Set the Application ID URI if it’s not set, then add a scope—such as access_as_user—defining specific permissions client apps can request.
This scope setup controls which parts of your API clients can access.
These steps establish your API as a trusted resource in Microsoft Entra ID, enabling OAuth 2.0 authorization. It’s a foundational move for securing your API with token-based authentication that enforces client permissions effectively.
Verification involves confirming the app registration appears with correct IDs and that the scope is properly defined and published. If this registration isn't accurate, OAuth flows won't function properly in later steps.
Sources: Quickstart: Protect an ASP.NET Core Web API.
Create a New ASP.NET Core Web API Project with Authentication
To create a new ASP.NET Core Web API project ready for OAuth 2.0 authentication with Microsoft Entra ID, start by opening your development environment with the .NET 9 SDK installed. Run the following command in your terminal or command prompt:
dotnet new webapi --auth SingleOrg --name MyWebApiThis scaffolds a new Web API project named "MyWebApi" configured to authenticate users from a single Azure AD (Microsoft Entra) organization, aligning with your tenant registration from the previous step. The --auth SingleOrg option automatically sets up the project to use Azure AD authentication under the hood.
The result is a project with built-in middleware and configuration prepared to handle OAuth 2.0 bearer tokens issued by your Entra tenant. This setup alleviates manual configuration hassles and ensures your API will challenge incoming requests for valid tokens.
You can verify success by opening the project and looking in files like Program.cs or Startup.cs (depending on project template) to see authentication services configured, and appsettings.json entries referencing your tenant and client IDs (to be set next). If the project creation fails, confirm your .NET SDK installation and command syntax.
This step sets a solid foundation, making it easier to integrate OAuth 2.0 authentication control with the Microsoft Entra tenant you prepared.
Sources: Quickstart: Protect an ASP.NET Core Web API.
Configure Azure AD Settings in appsettings.json
To configure Azure AD settings in your ASP.NET Core Web API project, open the appsettings.json file in your project's root directory. Here, you need to specify your Microsoft Entra tenant ID and the client (application) ID from the API app registration you created earlier.
These identifiers connect your API to the correct identity tenant and application configuration.
Additionally, define the scopes your API exposes. For example, include the scope you set up like api://{client-id}/access_as_user under a key for valid scopes.
This allows your API to validate incoming tokens against the permissions you've defined.
This configuration is essential because it tells your application which Azure AD tenant to trust, what client ID it represents, and which scopes to expect for authorizing client requests. Without it, your API wouldn't correctly authenticate or enforce access based on the registered permissions.
After updating appsettings.json, ensure your project reads these settings, typically via the AzureAd section binding in your Program.cs or Startup.cs file. This linkage enables middleware to use this information when processing authentication tokens.
Verify success by running your API and checking logs or middleware behavior to ensure the tenant and client IDs are recognized and no related errors occur. If verification fails, recheck the IDs and JSON formatting for typos or missing fields.
Source: Quickstart: Protect an ASP.NET Core Web API (Microsoft Entra ID) provided detailed guidance on these configuration steps.
Sources: Quickstart: Protect an ASP.NET Core Web API.
Add Microsoft Identity Web API Package and Middleware
Begin by installing the Microsoft.Identity.Web NuGet package into your ASP.NET Core Web API project. This package provides seamless integration with Microsoft Entra ID for OAuth 2.0 authentication and authorization.
Once installed, open your Program.cs (or Startup.cs depending on your project template) and register the authentication services with:
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration, "AzureAd");This step configures the middleware to validate incoming bearer tokens according to your Azure AD settings defined earlier.
Next, in the request pipeline setup, make sure to add the authentication middleware before authorization:
app.UseAuthentication();
app.UseAuthorization();The order here is crucial: authentication verifies the token first, then authorization enforces access policies.
These middleware components ensure that all API requests are checked for valid tokens and that access control based on user identity and scopes can be enforced securely.
Once configured, your API is ready to authenticate and authorize client requests using the OAuth 2.0 framework backed by Microsoft Entra ID.
Sources: Quickstart: Protect an ASP.NET Core Web API.
Protect API Endpoints Using Authorization and Scope Attributes
Once your API project is set up with authentication middleware, the next step is to secure your API endpoints themselves. Apply the [Authorize] attribute to your API controllers or specific action methods to require that incoming requests present a valid OAuth 2.0 access token.
This attribute enforces general authentication, blocking unauthenticated calls.
For finer-grained access control, use the [RequiredScope] attribute to specify the exact OAuth scope (such as access_as_user) that a client must have in its token to access particular operations. This helps you enforce permissions at the API operation level, ensuring only authorized clients with the correct scope can perform sensitive actions.
Place [RequiredScope] on controller classes or individual methods depending on how specific you want the scope enforcement to be. This layered approach balances security enforcement with developer usability—authenticated clients gain access, but only within their granted permissions.
Remember that these attributes hinge on prior setup done in your Microsoft Entra tenant app registration and API configuration. This step integrates those permissions into your API runtime behavior, providing robust authentication and authorization thanks to OAuth 2.0.
You can verify success by running your API and attempting requests with tokens that do and do not have the required scopes. Only requests with valid tokens that include the necessary scope should succeed.
Source: Quickstart: Protect an ASP.NET Core Web API (Microsoft Entra ID)
Sources: Quickstart: Protect an ASP.NET Core Web API.
Run and Test the API Server
To run and test your OAuth 2.0–secured API server, start by launching the ASP.NET Core Web API project using the command dotnet run from your project directory. This spins up the API host configured to require valid tokens issued by your Microsoft Entra tenant.
Once running, send requests to your protected endpoints using a client that includes an OAuth 2.0 access token with the proper scope (for example, access_as_user). Doing so confirms that the API enforces authentication and respects the scope-based permissions you defined.
If unauthorized requests are made without tokens or with tokens lacking required scopes, the API should reject them with HTTP 401 Unauthorized or 403 Forbidden responses. You can verify the correct operation by checking these status codes and testing access with different tokens.
This step ensures your API is actively validating tokens and enforcing authorization rules according to your OAuth 2.0 setup with Microsoft Entra ID, balancing security with developer usability as intended.
Source: Quickstart: Protect an ASP.NET Core Web API (Microsoft Entra ID).
Sources: Quickstart: Protect an ASP.NET Core Web API.
Verify OAuth 2.0 Protection of ASP.NET Core Web API
To verify your OAuth 2.0 protection on the ASP.NET Core Web API, start by running the API server using dotnet run in your project directory. This activates the API, which should now require clients to present valid access tokens issued by your Microsoft Entra tenant.
Next, test accessing the secured endpoints with a client that includes an OAuth token containing the necessary scope (for example, access_as_user). Requests with valid tokens and scopes should be allowed, while any requests lacking tokens or with insufficient scopes must be denied access.
Confirm success by observing HTTP responses: authorized calls return results, whereas unauthorized attempts respond with 401 Unauthorized or 403 Forbidden status codes. This ensures the API enforces both authentication and fine-grained authorization as configured.
If unauthorized requests are accepted, double-check your middleware order, app registration scopes, and endpoint authorization attributes. Proper verification guarantees your API balances secure access control with smooth developer usability, as intended with OAuth 2.0 and Microsoft Entra ID integration.
Sources: Quickstart: Protect an ASP.NET Core Web API.
Troubleshooting Common OAuth 2.0 Implementation Issues
When implementing OAuth 2.0 to secure your ASP.NET Core Web API with Microsoft Entra ID, some common issues can occur. A frequent problem is misconfigured app registrations—double-check that your API's Application (client) ID and Directory (tenant) ID are correct and that the OAuth scopes you exposed match those referenced in your API configuration.
Missing or mismatched scopes often cause authorization failures.
Another common pitfall is incorrect middleware order in your API project. Make sure that in your request pipeline, you call UseAuthentication() before UseAuthorization().
If reversed, the API will not properly authenticate tokens before enforcing authorization policies, leading to unexpected access denials.
Also, verify that the Microsoft.Identity.Web package is properly installed and that you registered the authentication services using AddMicrosoftIdentityWebApiAuthentication with your configuration section. Omitting or misconfiguring these steps can cause your API to reject all token-based requests.
If you run into authorization failures despite valid tokens, confirm that you have applied [Authorize] and [RequiredScope] attributes properly on your controllers or action methods. These attributes enforce that the request must include OAuth tokens with the right scopes.
Missing these attributes will result in unsecured endpoints or unintended access.
In case of persistent issues, check your appsettings.json for typos and ensure the tenant ID, client ID, and scope URIs align exactly with your Entra app registration definitions. Logs and HTTP 401/403 error responses are good indicators to help diagnose what part of the OAuth flow is failing.
By systematically validating app registrations, middleware sequence, package setup, and authorization attributes, you can resolve most implementation problems and achieve a secure, manageable OAuth 2.0–protected API.
Next steps
Following these steps lets you implement OAuth 2.0 protection for your ASP.NET Core Web API using Microsoft Entra ID effectively. Verify that your API only accepts requests bearing valid access tokens with required scopes, enforcing secure and fine-grained authorization.
If you encounter authorization issues, check your app registration details, middleware order, and attribute usage. Properly completed, this setup balances robust security with manageable developer usability, making it a solid choice for securing APIs in Microsoft-oriented environments.