Using Microsoft Entra ID in a .NET API

In this blog, we’ll explore how to configure a .NET REST API to authenticate requests using Microsoft Entra ID (formerly known as Azure AD). With a step-by-step guide, we’ll cover everything from configuration and authentication setup to enabling OAuth2 Authorization Code Flow with PKCE for interactive API testing in Scalar (OpenAPI UI).

You’ll learn how to:
• Authenticate API calls with Microsoft Entra ID-issued JWTs
• Enable OAuth2 Authorization Code flow from Scalar UI (OpenAPI) using PKCE
• Maintain compatibility with existing template toggles via compile-time symbol ExtLogin

Let’s dive into the details of getting this all set up.

What this Setup Provides

• Authenticate REST API calls with Microsoft Entra ID-issued JWTs
• Enable OAuth2 Authorization Code flow from Scalar UI (OpenAPI) using PKCE
• Keep compatibility with our existing template toggles via compile-time symbol ExtLogin

Prerequisites

  • An App Registration for the API
  • Exposed API permissions (scopes), such as api://{api-client-id}/Scalar and/or api://{api-client-id}/default
  • The API’s Client (Application) ID and Tenant ID
  • Issuer/authority details, e.g. https://login.microsoftonline.com/{tenantId}/v2.0

Configuration Model: OpenIdOptions

A dedicated options model holds the OpenID Connect settings for Entra ID:

public class OpenIdOptions
{
    public string Url { get; set; } = string.Empty;        // Authority
    public string IssuerUri { get; set; } = string.Empty;  // Issuer
    public string Scope { get; set; } = string.Empty;      // Optional default scope name
    public bool ValidateAudience { get; set; } = false;
    public string? ValidAudience { get; set; }
    public bool ValidateIssuer { get; set; } = true;
    public bool ValidateIssuerSigningKey { get; set; } = true;

    // Optional: map roles/groups from a custom claim name
    public string? RoleClaim { get; set; }

    // Used by OAuth for Scalar and OIDC flows
    public string ClientId { get; set; } = string.Empty;
    public string TenantId { get; set; } = string.Empty;
}

App Configuration: OpenIdSettings

Add the Entra ID configuration to appsettings.json (or secrets/environment config). Example:

{
  "OpenIdSettings": {
    "Url": "https://login.microsoftonline.com/{tenant-id}/v2.0",
    "IssuerUri": "https://login.microsoftonline.com/{tenant-id}/v2.0",
    "ValidateAudience": true,
    "ValidAudience": "api://{api-client-id}",
    "ValidateIssuer": true,
    "ValidateIssuerSigningKey": true,
    "RoleClaim": "roles",               // or "groups" if you map group IDs to roles
    "ClientId": "{api-client-id}",
    "TenantId": "{tenant-id}"
  }
}
  • Url (authority) and IssuerUri should match the tokens you will receive (v2 endpoints recommended).
  • If you validate audience, set ValidAudience to your API’s “Application ID URI” (often api://{clientId} or a custom URI).
  • RoleClaim is optional and used if you want to convert Entra roles/groups claims into your internal Role[] enum.

Configuring JWT Authentication

Add JWT bearer authentication so the API trusts tokens issued by Entra ID:

private static IServiceCollection AddAuthentication(this IServiceCollection srv, IConfiguration configuration)
{
    JwtSecurityTokenHandler.DefaultMapInboundClaims = false; // keep standard JWT claim names

    srv.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
       .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
       {
           var ido = configuration.GetSection(ConfigurationKeys.OpenIdOptions).Get<OpenIdOptions>();
           options.Authority = ido.Url; // e.g. https://login.microsoftonline.com/{tenantId}/v2.0
           options.TokenValidationParameters = new TokenValidationParameters
           {
               ValidateLifetime = true,
               ClockSkew = TimeSpan.FromSeconds(5),
               ValidateAudience = ido.ValidateAudience,
               ValidAudience = ido.ValidAudience,
               ValidateIssuer = ido.ValidateIssuer,
               ValidateIssuerSigningKey = ido.ValidateIssuerSigningKey,
               ValidIssuer = ido.IssuerUri
           };
       });

    return srv;
}

This instructs the API to accept and validate JWTs issued by Entra ID for your tenant and API audience.

OpenAPI/Scalar: OAuth2 Authorization Code Flow with PKCE

Scalar (OpenAPI UI) can be configured for interactive testing with Entra ID. This requires an OAuth2 AuthorizationCode flow definition with PKCE.

Example OpenAPI Transformer


internal sealed class OpenApiSecuritySchemeTransformer(IConfiguration cfg) : IOpenApiDocumentTransformer
{
    private const string AuthenticationScheme = "Bearer";

    public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
    {
        var options = cfg.GetSection(ConfigurationKeys.OpenIdOptions).Get<OpenIdOptions>()
            ?? throw new InvalidOperationException($"{ConfigurationKeys.OpenIdOptions} should be configured for OAuth to work");

        var tenantId = options.TenantId;
        var apiClientId = options.ClientId;
        var apiAccessScope = $"api://{apiClientId}/Scalar";   // example exposed scope
        var defaultScope = $"api://{apiClientId}/default";    // optional

        var securitySchema = new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.OAuth2,
            Scheme = AuthenticationScheme,
            BearerFormat = "JWT",
            Flows = new OpenApiOAuthFlows
            {
                AuthorizationCode = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"),
                    TokenUrl = new($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
                    Scopes = new Dictionary<string, string>
                    {
                        [apiAccessScope] = "Access Demo API",
                        [defaultScope] = "Default access",
                        ["openid"] = "OpenID",
                        ["profile"] = "Profile access"
                    },
                    Extensions = new Dictionary<string, IOpenApiExtension>()
                    {
                        ["x-usePkce"] = new OpenApiString("SHA-256"),
                    }
                }
            }
        };

        document.SecurityRequirements.Add(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference { Id = AuthenticationScheme, Type = ReferenceType.SecurityScheme }
                },
                [apiAccessScope]
            }
        });

        document.Components = new OpenApiComponents
        {
            SecuritySchemes = new Dictionary<string, OpenApiSecurityScheme> { { AuthenticationScheme, securitySchema } }
        };

        return Task.CompletedTask;
    }
}

Scalar UI Wiring and Selecting Scopes

public static IEndpointRouteBuilder MapScalar(this IEndpointRouteBuilder builder, IConfiguration cfg)
{
    var openIdOptions = cfg.GetSection(ConfigurationKeys.OpenIdOptions).Get<OpenIdOptions>()
        ?? throw new InvalidOperationException($"{ConfigurationKeys.OpenIdOptions} should be configured for Scalar to work");

    builder.MapScalarApiReference(options =>
    {
        options.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
        options.AddAuthorizationCodeFlow(JwtBearerDefaults.AuthenticationScheme, flow =>
        {
            flow.ClientId = openIdOptions.ClientId;
            flow.SelectedScopes = [$"api://{openIdOptions.ClientId}/Scalar"];
        });
    });
    return builder;
}

App Startup

srv.AddOpenApi(options =>
        {
            options.AddDocumentTransformer<OpenApiSecuritySchemeTransformer>();
        });

app.MapOpenApi();
app.MapScalar(app.Configuration);

Now you can “Authorize” directly in Scalar, complete the PKCE flow against Entra ID, and have the UI attach access tokens to calls.

Common Pitfalls and Troubleshooting

  • Audience/issuer mismatch:
    • Ensure the API’s “Application ID URI” matches ValidAudience and the aud in your tokens.
    • Use v2.0 endpoints consistently for both authorize and token URLs.
  • Role vs. group claims:
    • If you configured App Roles, users get roles claim. Map RoleClaim = “roles” and align enum names.
    • If you rely on Entra groups, you’ll get groups claim with GUID values. Maintain a GUID→role map.
  • Claim mapping surprises:
    • Keep JwtSecurityTokenHandler.DefaultMapInboundClaims = false to avoid legacy claim URI remapping.
  • Scalar not showing “Authorize” or failing:
    • Verify OpenIdSettings are present.
    • Confirm the scope used in SelectedScopes is actually exposed by your API app registration and granted to users.

Summary

To integrate Microsoft Entra ID with a .NET API:

  • Define an OpenIdOptions model and configure it from appsettings.
  • Add JWT bearer authentication pointing to Entra ID’s authority.
  • Configure Scalar/OpenAPI for OAuth2 Authorization Code flow with PKCE.
  • Map roles or groups based on your organization’s identity policy.

Use the code snippets above as a starting point, adjust scopes and claims to your organization’s policy, and you’ll have a production-ready, Entra-backed API flow end-to-end.

Also, you can feel free to contact Trailhead for any advice relate to topic!

Picture of Aleksandar Dickov

Aleksandar Dickov

Aleksandar is a seasoned professional with a decade of experience in software development. He holds a B.S. in Computer Science from the Faculty of Technical Science. Throughout his career, he has actively contributed to the creation of web and desktop applications, acquiring proficiency in languages such as C# and a strong command of the .NET platform. Thriving on the challenge of solving complex problems, Aleksandar is known for his result-oriented approach and unwavering dedication to delivering impactful solutions. His passion for software development extends beyond the professional realm, believing in the continuous pursuit of knowledge to enhance his contributions to any team. Beyond the world of coding, Aleksandar finds joy in basketball, football, and skiing. Whether it's exploring new places, engaging in sports, or maintaining a blog, he embraces a well-rounded approach to life.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.