Azure

Securing APIs with Microsoft Entra ID: scope, client and token validation

A practical guide to protecting an API with Microsoft Entra ID: registering the API, exposing a scope, and registering the client that requests it. It walks through a .NET Core API using Microsoft.Identity.Web, a React client using MSAL, and a .NET web app calling a downstream API. The same token checks apply to any backend stack.

DEV Community: #dotnet Bilal Haidar
Published
Reading time
4 min read
agent run #17
agent run #17
Go to original dev.to

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Key points

  • Define a scope such as access_as_user under Expose an API in the API registration, and set requestedAccessTokenVersion to 2 in the manifest.
  • In the client registration, add that scope under API permissions as Delegated and grant admin consent.
  • Use AddMicrosoftIdentityWebApi and enforce the scope with RequireScope or [RequiredScope] on endpoints.
  • Send only access tokens to the API; ID tokens are meant for the client.
  • Do not put client secrets in SPAs; they should run as public clients with PKCE.
  • For a 401 'invalid audience' error, compare the scope the client requests with the API's Audience setting.

The article explains how to connect an API and its clients through Microsoft Entra ID. The API publishes a delegated scope, each client requests it, and Entra ID issues an access token for the API's audience. The API only has to validate the token's signature, issuer, audience and scp claim, so it never handles user passwords.

The examples cover JWT validation in a .NET API with Microsoft.Identity.Web, token acquisition in a React single-page app with MSAL, and a .NET web app calling a downstream API through IDownstreamApi. The author also covers requesting v2 tokens, admin consent or pre-authorizing clients, and the common 401 and AADSTS65001 errors. The same checks apply to non-.NET backends using the tenant's discovery keys. The original post has the full configuration and code.

Real-world use

  • Protecting an ASP.NET Core orders API with access tokens issued to a React SPA for signed-in users.
  • Letting an MVC web app call a downstream API on behalf of the user with IDownstreamApi.
  • Connecting a Node, Python or Laravel backend to the same Entra ID scope model.

Why it matters

Using one scope model in Entra ID lets you manage trust between clients and APIs through standard token checks. Getting the access token versus ID token distinction and the audience and scp validation right prevents common production authorization bugs.

This summary was generated by the agent from the original post on DEV Community: #dotnet. The full text and all rights belong to its author and publisher. Go to original

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message