OIDC Sign-In and Token Management with Entra ID in a Web Application

SSO for a web app with Entra ID OIDC: authorization code + PKCE, app registration, token storage (BFF), authorization with app roles, sign-out and AADSTS errors.
Technical summary
Technology
Microsoft Entra ID, OpenID Connect, OAuth 2.0, PKCE (RFC 7636), MSAL, Microsoft.Identity.Web
Topic
Corporate SSO and token management for a web application
Level
Intermediate–advanced
Prerequisites
  • Permission to create app registrations in Entra ID
  • Knowledge of HTTP redirects and cookies
  • Familiarity with JWT structure
In this article7 sections

Adding “sign in with a Microsoft account” to an internal web application looks like a few lines of library configuration. It isn’t. Which flow is chosen, where tokens are kept and which claim authorization is read from directly determine the app’s security level. Below, we cover OpenID Connect (OIDC) sign-in with Microsoft Entra ID from start to finish: the authorization code + PKCE flow, app registration, token types and storage, role-based authorization, sign-out and the AADSTS error codes that come up most often in the field.

OIDC and OAuth 2.0 roles

OAuth 2.0 (RFC 6749) is an authorization framework: it allows a client to access a resource on behalf of a user. OpenID Connect adds an identity layer on top of it and defines the ID token, which tells the client who the user is. In the Entra ID scenario, the roles map like this:

Role In the Entra ID scenario
OpenID Provider / authorization server Microsoft identity platform (login.microsoftonline.com)
Relying Party / client Your web application (app registration)
Resource server Your own API or Microsoft Graph
Resource owner The signed-in user

Making this distinction clear cuts off the mistake we see most often in code reviews: authenticating (ID token) and getting permission to access an API (access token) are different jobs done with different tokens. The ID token isn’t sent to an API. Which permissions the app uses to access Microsoft Graph is a separate design topic; we explained it in the Microsoft Graph API permissions article. The topic here is the user’s sign-in flow to the app.

The authorization code + PKCE flow

The recommended flow for web applications is the authorization code flow strengthened with PKCE (RFC 7636). The implicit flow, formerly used in single-page apps, is no longer recommended because it carries the token in the URL fragment. The steps of the flow:

  1. The app generates a random code_verifier and calculates the base64url encoding of its SHA-256 hash as the code_challenge. It also generates a state value against CSRF and a nonce value against replay, and stores them in the user’s session.
  2. The browser is redirected to the authorization endpoint (there’s a URL-encoded example request below).
  3. The user authenticates in Entra ID; Conditional Access policies and MFA are applied at this stage.
  4. Entra ID sends the browser back to the registered redirect URI with a code and state.
  5. The app validates the state value and exchanges the code for tokens at the token endpoint with the code_verifier and the client credential.
  6. The ID token’s signature and the iss, aud, exp and nonce values are validated; the app creates its own session.
GET https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize
  ?client_id={client-id}
  &response_type=code
  &redirect_uri=https%3A%2F%2Fportal.example.com%2Fsignin-oidc
  &response_mode=form_post
  &scope=openid%20profile%20offline_access
  &state={random-state}
  &nonce={random-nonce}
  &code_challenge={code-challenge}
  &code_challenge_method=S256

Don’t code these steps by hand. Use a mature library: Microsoft.Identity.Web for ASP.NET Core, MSAL Node or a standard OIDC client library for Node.js. The basic configuration in ASP.NET Core looks like this:

// Program.cs
builder.Services
    .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

// appsettings.json
"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "TenantId": "{tenant-id}",
  "ClientId": "{client-id}",
  "CallbackPath": "/signin-oidc"
  // The client credential for exchanging the code for tokens and calling APIs
  // is defined under "ClientCredentials" (a certificate is preferred)
}

Write your own tenant ID as the tenant instead of common or organizations. That way, sign-in attempts with accounts from other organizations are shut off from the start in an internal app.

App registration and redirect URIs

The registration created under App registrations in the Entra admin center is the app’s identity. Settings to check one by one during setup:

  • Supported account types: For an internal app, “accounts in this organizational directory only” (single tenant).
  • Platform type: Web for a server-side app; Single-page application for a single-page app that gets tokens directly from the browser. The wrong platform type is the most common cause of the error codes below.
  • Redirect URIs: An exact match is required, including scheme, domain, port, path and trailing slash. HTTPS is mandatory except for localhost. Create separate registrations for development, test and production; otherwise test addresses get forgotten in the production registration.
  • Implicit grant options: In the authorization code flow, the “ID tokens” and “Access tokens” checkboxes should stay unticked.
  • Client credential: Prefer a certificate over a client secret, and federated/managed identity where possible. If you use a secret, tie its expiry date to a calendar and a monitoring record. An expired secret locks all users out one morning.
  • User assignment: When “Assignment required?” is turned on under Enterprise applications, only assigned users and groups can sign in.

Token types and secure storage

Token Purpose Who consumes it
ID token The user’s identity and session information Client app
Access token Access to a specific API The target API (the aud value)
Refresh token Getting a new access token without user interaction Only the client, sending it to the token endpoint

On the Microsoft identity platform, the default lifetime of access tokens is kept short and they’re renewed with a refresh token; refresh tokens issued on the single-page application platform have an even shorter lifetime. Microsoft may update these periods. Don’t assume fixed durations in code; use the expires_in and exp values.

There are two main patterns for the storage decision:

  • BFF (backend for frontend): Tokens are kept only on the server, in the session store; the browser receives only a session cookie with the HttpOnly, Secure and SameSite=Lax (or Strict) attributes. API calls go through the BFF. Even with XSS, the attacker can’t read the token. This is the default choice for corporate applications. In Next.js web applications using the App Router, this pattern is set up by keeping tokens only in server modules; we explained how to draw the boundary in the Server and Client Components in the Next.js App Router article.
  • Tokens in the browser: MSAL Browser keeps tokens in sessionStorage by default. No separate server layer is needed; but every script running on the page can access the token. If this pattern is chosen, a content security policy (CSP), third-party script control and short token lifetimes become mandatory. Don’t use localStorage.

When your own API validates an access token, it should compare: the signature against the key from the tenant’s JWKS endpoint, the iss value against your tenant, the aud value against the API’s app ID/URI, and the scp or roles claims against the expected permissions. When matching the user in the app database, oid and tid are used together, not email. Email changes; oid doesn’t.

Authorization from app roles and group claims

There are two sources for authorization: app roles and group claims. App roles are defined on the registration (the App roles section; for example Request.Create, Request.Approve, Admin), assigned to users or groups through the enterprise application and arrive in the token as the roles claim. Since role names are app-specific and meaningful, the code stays readable:

[Authorize(Roles = "Request.Approve")]
public IActionResult Approve(Guid requestId) { ... }

Group claims (Token configuration > Add groups claim) carry group object IDs. They have two limitations: working with a list of GUIDs in code gets harder, and if the user is a member of many groups, an “overage” indicator is put in the token instead of the groups. In a JWT this limit is 200 groups; when it’s exceeded, the app has to query the groups separately from Microsoft Graph. Code that works with a three-group user in the test environment breaks in production for a manager who is a member of hundreds of groups. That’s why the order of preference is clear: app roles first; if groups are required, the “groups assigned to the application only” option. For combining the role model with the data layer in portals that need customer-based authorization, see the B2B portal authorization architecture article.

Sign-out and common errors

Sign-out has two layers: deleting the app’s own session cookie and redirecting the user to Entra ID’s sign-out endpoint (/oauth2/v2.0/logout) with the post_logout_redirect_uri parameter. If you delete only the local cookie, the Entra session stays open; when the user clicks “Sign in”, they’re silently let back in. On shared devices this difference is a serious problem. If a front-channel logout URL is defined in the app registration, Entra ID calls this address when the user signs out of another app, and the app can clear the local session.

The error codes seen most often in the field and what they mean:

Code Meaning Typical fix
AADSTS50011 The redirect URI doesn’t match the registration Fix the scheme/host information behind the reverse proxy, add the URI exactly
AADSTS700054 The id_token response type isn’t enabled Switch the library to the code flow
AADSTS65001 User or admin consent hasn’t been given Grant admin consent for the permissions
AADSTS50105 The user isn’t assigned to the app Assign the user or their group to the app
AADSTS7000215 Invalid client secret Use the secret’s value (not its ID), check its expiry
AADSTS9002326 Cross-origin token redemption is only possible for the SPA type Move the redirect URI to the correct platform type

The most common source of AADSTS50011 is setups where TLS is terminated at the reverse proxy and the app thinks it’s running on http://. The app generates the redirect URI with http, the registration has https, and the match fails. The original scheme and host information must be passed to the app with the ForwardedHeaders middleware in ASP.NET Core and the proxy trust (trust proxy) setting in Node.js. For the full description of an error code, enter the code on the login.microsoftonline.com/error page.

Checklist before going live:

  • Single tenant, the correct platform type and a separate app registration per environment.
  • state, nonce and PKCE are enabled by the library; implicit grant is off.
  • Tokens are in the BFF; only an HttpOnly and Secure cookie in the browser.
  • User matching is by oid + tid; authorization comes from app roles.
  • On sign-out, both the local session and the Entra session are ended.
  • The client secret/certificate expiry date is monitored.

The strength of sign-in depends on the authentication method on the Entra ID side; for moving to phishing-resistant methods, see the FIDO2 and passkey migration plan article. When adding SSO and role-based authorization to your internal application, we can design the flow and the token storage pattern together within the scope of our custom web application development service. For detailed reference, the Microsoft identity platform documentation and RFC 7636 should be the basis.

Frequently asked questions

Is PKCE needed in a server-side web application too?

It isn’t mandatory, but it’s recommended. In confidential clients using a client secret or certificate, PKCE provides extra protection against the authorization code being intercepted and used in another session. OAuth 2.0 security best practices (RFC 9700) recommend PKCE for confidential clients too; current MSAL libraries support it.

Which claim should I use to match the user in the application database?

For permanent and unique matching, oid (object ID) is used together with tid (tenant ID). preferred_username, upn or email can change or be reassigned to another user; use them only for display.

When is removing a user from a role reflected in the app?

Since roles and groups are written as claims when the token is issued, the change isn’t reflected until the app gets a new token. If the app keeps its own session cookie valid for a long time, the delay is even longer. For sensitive permissions, keep the session short or require re-authentication before the operation.

Should I decode and validate the access token I get from Microsoft Graph in the app?

No. Microsoft recommends that access tokens issued for another resource such as Graph be treated as opaque by the client and not parsed; their format can change without notice. The client gets user information from the ID token; your own API validates only the access token issued for it.

Support

Contact us for support or a discovery session on this topic.

Contact form
[email protected]

Eretek Web

We build and maintain corporate websites, WordPress and CMS platforms, intranet and SharePoint portals, document management, and form and approval workflows, and keep them secure and up to date.

Knowledge Center

Other articles