Overview:
This post uses a sample Angular single-page app (SPA) to demonstrate how to sign in users using the authorization code flow with Proof Key for Code Exchange (PKCE).
The sample leverages the Microsoft Authentication Library for JavaScript (MSAL) to handle authentication.
Prerequisites include an Azure account and Node.js.
Steps include registering the application, recording identifiers, adding a platform redirect URI, and configuring the project.
The SPA can then call the Microsoft Graph API securely.
Let’s get started.
What is Microsoft identity platform and OAuth 2.0 authorization code flow
The OAuth 2.0 authorization code grant type, or auth code flow, enables a client application to obtain authorized access to protected resources like web APIs.
The auth code flow requires a user-agent that supports redirection from the authorization server (the Microsoft identity platform) back to your application. For example, a web browser, desktop, or mobile application operated by a user to sign in to your app and access their data.
This article describes low-level protocol details required only when manually crafting and issuing raw HTTP requests to execute the flow, which we do not recommend. Instead, use a Microsoft-built and supported authentication library to get security tokens and call protected web APIs in your apps.
Applications that support the auth code flow
Use the auth code flow paired with Proof Key for Code Exchange (PKCE) and OpenID Connect (OIDC) to get access tokens and ID tokens in these types of apps:
Protocol details.
The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. Apps using the OAuth 2.0 authorization code flow acquire an access_token to include in requests to resources protected by the Microsoft identity platform (typically APIs). Apps can also request new ID and access tokens for previously authenticated entities by using a refresh mechanism.
This diagram shows a high-level view of the authentication flow:

Redirect URIs for single-page apps (SPAs)
Redirect URIs for SPAs that use the auth code flow require special configuration.
- Add a redirect URI that supports auth code flow with PKCE and cross-origin resource sharing (CORS): Follow the steps in Redirect URI: MSAL.js 2.0 with auth code flow.
- Update a redirect URI: Set the redirect URI’s
typetospaby using the application manifest editor in the Microsoft Entra admin center.
The spa redirect type is backward-compatible with the implicit flow. Apps currently using the implicit flow to get tokens can move to the spa redirect URI type without issues and continue using the implicit flow.
If you attempt to use the authorization code flow without setting up CORS for your redirect URI, you’ll see this error in the console:
access to XMLHttpRequest at ‘https://login.microsoftonline.com/common/v2.0/oauth2/token’ from origin ‘yourApp.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
If so, visit your app registration and update the redirect URI for your app to use the spa type.
Applications can’t use a spa redirect URI with non-SPA flows, for example, native applications or client credential flows. To ensure security and best practices, the Microsoft identity platform returns an error if you attempt to use a spa redirect URI without an Origin header. Similarly, the Microsoft identity platform also prevents the use of client credentials in all flows in the presence of an Origin header, to ensure that secrets aren’t used from within the browser.
Request an authorization code
The authorization code flow begins with the client directing the user to the /authorize endpoint. In this request, the client requests the openid, offline_access, and https://graph.microsoft.com/mail.read permissions from the user.
Some permissions are admin-restricted, for example, writing data to an organization’s directory by using Directory.ReadWrite.All. If your application requests access to one of these permissions from an organizational user, the user receives an error message that says they’re not authorized to consent to your app’s permissions. To request access to admin-restricted scopes, you should request them directly from a Global Administrator. For more information, see Admin-restricted permissions.
Unless specified otherwise, there are no default values for optional parameters. There is, however, default behavior for a request omitting optional parameters. The default behavior is to either sign in the sole current user, show the account picker if there are multiple users, or show the login page if there are no users signed in.
//
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=00001111-aaaa-2222-bbbb-3333cccc4444
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
&state=12345
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=S256
Successful response
This example shows a successful response using response_mode=query:
GET http://localhost?
code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
&state=12345
Demo
Prerequisites
- An Azure account with an active subscription. If you don’t already have one, Create an account for free.
- Node.js
- Visual Studio 2022 or Visual Studio Code
Demo(Summary):
- Register the application and record identifiers
- Add a platform redirect URI
- Clone or download the sample application
- Configure the project
- Run the application and sign in
- Validate
Demo(Step-by-step):
Register the application and record identifiers
To complete registration, provide the application a name, specify the supported account types, and add a redirect URI. Once registered, the application Overview pane displays the identifiers needed in the application source code.
- Sign in to the Microsoft Entra admin center.
- If you have access to multiple tenants, use the Settings icon in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
- Browse to Identity > Applications > App registrations, select New registration.
- Enter a Name for the application, such as identity-client-spa.
- For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
- Select Register.

The application’s Overview pane is displayed when registration is complete. Record the Directory (tenant) ID and the Application (client) ID to be used in your application source code.

Add a platform redirect URI
To specify your app type to your app registration, follow these steps:
- Under Manage, select Authentication.
- On the Platform configurations page, select Add a platform, and then select SPA option.
- For the Redirect URIs enter
http://localhost:4200. - Select Configure to save your changes.
Clone or download the sample application
To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.
- To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:
ConsoleCopy
git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript.git
- Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.
Configure the project
- In your IDE, open the project folder, ms-identity-docs-code-javascript/angular-spa, containing the sample.
- Open src/app/app.module.ts and update the following values with the information recorded earlier in the admin center.
JavaScriptCopy
JavaScriptCopy
// Required for Angular multi-browser support
import { BrowserModule } from '@angular/platform-browser';
// Required for Angular
import { NgModule } from '@angular/core';
// Required modules and components for this application
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProfileComponent } from './profile/profile.component';
import { HomeComponent } from './home/home.component';
// HTTP modules required by MSAL
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
// Required for MSAL
import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser';
import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular';
const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication({
auth: {
// 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID
clientId: "Enter_the_Application_Id_Here",
// Full directory URL, in the form of https://login.microsoftonline.com/<tenant>
authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
// Must be the same redirectUri as what was provided in your app registration.
redirectUri: "http://localhost:4200",
},
cache: {
cacheLocation: BrowserCacheLocation.LocalStorage,
storeAuthStateInCookie: isIE
}
});
}
// MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph)
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
return {
interactionType: InteractionType.Redirect,
protectedResourceMap
};
}
// MSAL Guard is required to protect routes and require authentication before accessing protected routes
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
authRequest: {
scopes: ['user.read']
}
};
}
// Create an NgModule that contains the routes and MSAL configurations
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ProfileComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
MsalModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: MSAL_INSTANCE,
useFactory: MSALInstanceFactory
},
{
provide: MSAL_GUARD_CONFIG,
useFactory: MSALGuardConfigFactory
},
{
provide: MSAL_INTERCEPTOR_CONFIG,
useFactory: MSALInterceptorConfigFactory
},
MsalService,
MsalGuard,
MsalBroadcastService
],
bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule { }
clientId– The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.authority– The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
redirectUri– The Redirect URI of the application. If necessary, replace the text in quotes with the redirect URI that was recorded earlier.
Run the application and sign in
Run the project with a web server by using Node.js:
- To start the server, run the following commands from within the project directory:
npm install
npm start- Copy the
httpsURL that appears in the terminal, for example,https://localhost:4200, and paste it into a browser address bar. We recommend using a private or incognito browser session. - Follow the steps and enter the necessary details to sign in with your Microsoft account. You’ll be requested an email address so a one time passcode can be sent to you. Enter the code when prompted.
- The application will request permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select Accept. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
Validate

Recap:
This document provides a step-by-step guide on how to sign in users using the authorization code flow with Proof Key for Code Exchange (PKCE) in an Angular single-page app (SPA). The sample application is built on the Angular framework and leverages the Microsoft Authentication Library for JavaScript (MSAL) to handle authentication.
Prerequisites
To complete this guide, the following prerequisites are required:
1. Azure Account: You must have an Azure account to register the application and generate the necessary tokens.
2. Node.js: The Angular app requires Node.js to be installed.
Steps to Implement Sign-In
1. Register the Application: Start by registering the application in Azure. This will create a client ID and secret that will be used to authenticate with Azure.
2. Record Identifiers: After registering the application, record the following identifiers: client ID, tenant ID, and authority URL. These will be used to authenticate with the Microsoft Graph API securely.
3. Add a Platform Redirect URI: Next, add a platform redirect URI to your application registration. This URI will be used to receive the authorization code during the sign-in process.
4. Configure the Project: Configure the Angular project by adding the necessary dependencies and configuring the authentication settings.
5. Call the Microsoft Graph API Securely: With the authentication set up, the SPA can now securely call the Microsoft Graph API to retrieve user data and perform other operations.
By following these steps, you will have successfully implemented sign in for your Angular SPA using the authorization code flow with PKCE. The sample application provided in this document serves as a starting point for developers to build upon and customize for their own needs.
Conclusion
In summary, this post provides developers with a practical guide to implementing secure sign-in functionality in Angular SPAs using the Microsoft identity platform. By following the steps outlined in the post, you can enhance your application’s security and seamlessly integrate with Microsoft Graph services.
Happy coding!
🚀🔐👨💻
References:
https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-single-page-app-angular-sign-in
