CodexBloom - Programming Q&A Platform

How to Set Up Azure API Management with OAuth2 for a .NET Core Web API?

👀 Views: 68 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
azure oauth2 api-management dotnet-core csharp

I'm performance testing and I'm trying to secure my .NET Core Web API using Azure API Management (APIM) with OAuth2 authentication, but I keep running into issues during the token acquisition process... I've configured my Azure AD app registration with the necessary permissions and set up the APIM to require OAuth2, but I receive a `401 Unauthorized` behavior when trying to access the API endpoints. Here's what I've done so far: 1. Registered my API in Azure AD and noted the Application (client) ID and Directory (tenant) ID. 2. Set up a client secret for my API app registration and included it in my app's configuration. 3. Configured API Management to use OAuth 2.0 with the following settings: - Authorization URL: `https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token` - Client ID: `{clientId}` - Client Secret: `{clientSecret}` - Scope: `api://{clientId}/.default` In my .NET Core application, I'm using the following code to acquire the token: ```csharp var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"); var body = new FormUrlEncodedContent(new Dictionary<string, string> { { "client_id", "{clientId}" }, { "client_secret", "{clientSecret}" }, { "scope", "api://{clientId}/.default" }, { "grant_type", "client_credentials" } }); request.Content = body; var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); Console.WriteLine(json); } else { Console.WriteLine($"behavior: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}"); } ``` When I run this code, I get a `400 Bad Request` behavior, and the response includes the message: `invalid_scope`. I've double-checked the scope and the application permissions; they seem to be set correctly. I also tried changing the scope to just `api://{clientId}/` and removing the `.default`, but that did not resolve the scenario either. Any insights into what might be going wrong here or additional configurations I might be missing in Azure APIM for OAuth2 integration? I'd really appreciate any guidance on this.