Angular single-page application using MSAL Angular to sign-in users against Microsoft Entra External ID
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Contributing
- Learn More
Overview
This sample demonstrates an Angular single-page application (SPA) that lets users sign-in with Microsoft Entra External ID using the Microsoft Authentication Library for Angular (MSAL Angular).
Here you'll learn about ID Tokens, OIDC scopes, single-sign on, silent requests and more.
Scenario
- The client Angular SPA uses the to sign-in a user and obtain a JWT ID Token from Microsoft Entra External ID.
- The ID Token proves that the user has successfully authenticated against Microsoft Entra External ID.
Contents
File/folder | Description |
---|---|
src/app/auth-config.ts |
Authentication parameters reside here. |
src/app/app.module.ts |
MSAL Angular configuration parameters reside here. |
src/app/app-routing.module.ts |
Configure your MSAL-Guard here. |
Prerequisites
- Node.js must be installed to run this sample.
- Visual Studio Code is recommended for running and editing this sample.
- VS Code Azure Tools extension is recommended for interacting with Azure through VS Code Interface.
- A modern web browser.
- An external tenant. To create one, choose from the following methods:
- (Recommended) Use the Microsoft Entra External ID extension to set up an external tenant directly in Visual Studio Code.
- Create a new external tenant in the Microsoft Entra admin center.
- A user account in your external tenant.
This sample will not work with a personal Microsoft account. If you're signed in to the Microsoft Entra admin center with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
Setup the sample
Step 1: Clone or download this repository
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.git
or download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
Step 2: Install project dependencies
cd 1-Authentication\1-sign-in-angular\SPA
npm install
Step 3: Register the sample application(s) in your tenant
There is one project in this sample. To register it, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
> :warning: If you have never used **Microsoft Graph PowerShell** before, we recommend you go through the [App Creation Scripts Guide](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step.
1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory
1. In PowerShell run:
```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
```
1. Run the script to create your Azure AD application and configure the code of the sample application accordingly.
1. For interactive process -in PowerShell, run:
```PowerShell
cd .\AppCreationScripts\
.\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
```
> Other ways of running the scripts are described in [App Creation Scripts guide](./AppCreationScripts/AppCreationScripts.md). The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
Choose the external tenant where you want to create your applications
To manually register the apps, as a first step you'll need to:
- Sign in to the Microsoft Entra admin center.
- If your account is present in more than one external tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired external tenant.
Create User Flows
Please refer to: Tutorial: Create a sign-up and sign-in user flow
ℹ️ To enable password reset in an external tenant, please refer to: Tutorial: Enable users to unlock their account or reset passwords using Microsoft Entra self-service password reset
Add External Identity Providers
Please refer to:
Register the spa app (ciam-msal-angular-spa)
- Navigate to the Microsoft Entra admin center and select the CIAM service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
ciam-msal-angular-spa
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Single-page application option.
- In the Redirect URI section enter the following redirect URI:
http://localhost:4200
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URI:
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select openid, offline_access in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- At this stage, the permissions are assigned correctly, but since it's an external tenant, the users themselves cannot consent to these permissions. To get around this problem, we'd let the tenant administrator consent on behalf of all users in the tenant. Select the Grant admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all accounts in the tenant. You need to be a tenant admin to be able to carry out this operation.
Configure the spa app (ciam-msal-angular-spa) to use your app registration
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
SPA\src\app\auth-config.ts
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofciam-msal-angular-spa
app copied from the Microsoft Entra admin center. - Find the placeholder
Enter_the_Tenant_Subdomain_Here
and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain iscontoso.onmicrosoft.com
, usecontoso
. If you don't have your tenant domain name, learn how to read your tenant details.
Step 4: Running the sample
cd 1-Authentication\1-sign-in-angular\SPA
npm start
Explore the sample
- Open your browser and navigate to
http://localhost:4200
. - Select the Sign-in button on the top right corner. Once you sign-in, you will see some of the important claims in your ID token.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
We'd love your feedback!
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
Troubleshooting
Expand for troubleshooting info
- Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [
azure-active-directory-b2c
node
ms-identity
adal
msal-js
msal
].
To provide feedback on or suggest features for Microsoft Entra, visit User Voice page.
About the code
MSAL Angular is a wrapper around MSAL.js (i.e. msal-browser). As such, many of MSAL.js's public APIs are also available to use with MSAL Angular, while MSAL Angular itself offers additional public APIs.
Configuration
You can initialize your application in several ways, for instance, by loading the configuration parameters from another server. See Configuration options for more information.
In the sample, authentication parameters reside in auth-config.ts. These parameters then are used for initializing MSAL Angular configuration options in app.module.ts.
Sign-in
MSAL Angular exposes 3 login methods: loginPopup()
, loginRedirect()
and ssoSilent()
. First, setup your default interaction type in app.module.ts:
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
};
}
Then, define a login method in app.component.ts as follows:
export class AppComponent implements OnInit {
constructor(
@Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration,
private authService: MsalService,
private msalBroadcastService: MsalBroadcastService
) {}
ngOnInit(): void {
login() {
if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
if (this.msalGuardConfig.authRequest) {
this.authService.loginPopup({...this.msalGuardConfig.authRequest} as PopupRequest)
.subscribe((response: AuthenticationResult) => {
this.authService.instance.setActiveAccount(response.account);
});
} else {
this.authService.loginPopup()
.subscribe((response: AuthenticationResult) => {
this.authService.instance.setActiveAccount(response.account);
});
}
} else {
if (this.msalGuardConfig.authRequest) {
this.authService.loginRedirect({...this.msalGuardConfig.authRequest} as RedirectRequest);
} else {
this.authService.loginRedirect();
}
}
}
}
If you already have a session that exists with the authentication server, you can use the ssoSilent()
API to make a request for tokens without interaction. You will need to pass a loginHint in the request object in order to successfully obtain a token silently.
export class AppComponent implements OnInit {
constructor(
private authService: MsalService,
) {}
ngOnInit(): void {
const silentRequest: SsoSilentRequest = {
scopes: ["User.Read"],
loginHint: "user@contoso.com"
}
this.authService.ssoSilent(silentRequest)
.subscribe({
next: (result: AuthenticationResult) => {
console.log("SsoSilent succeeded!");
},
error: (error) => {
this.authService.loginRedirect();
}
});
}
}
ID Token Validation
When you receive an ID token directly from the IdP on a secure channel (e.g. HTTPS), such is the case with SPAs, there’s no need to validate it. If you were to do it, you would validate it by asking the same server that gave you the ID token to give you the keys needed to validate it, which renders it pointless, as if one is compromised so is the other.
Sign-out
The application redirects the user to the Microsoft identity platform logout endpoint to sign out. This endpoint clears the user's session from the browser. If your app did not go to the logout endpoint, the user may re-authenticate to your app without entering their credentials again, because they would have a valid single sign-in session with the Microsoft identity platform endpoint. For more information, see: Send a sign-out request.
Securing Routes
You can add authentication to secure specific routes in your application by just adding canActivate: [MsalGuard]
to your route definition. It can be added at the parent or child routes. This ensures that the user must be signed-in to access the secured route.
const routes: Routes = [
{
path: 'guarded',
component: GuardedComponent,
canActivate: [
MsalGuard
]
}
]
Events API
Using the event API, you can register an event callback that will do something when an event is emitted. When registering an event callback in an Angular component you will need to make sure you do 2 things.
- The callback is registered only once
- The callback is unregistered before the component unmounts.
export class HomeComponent implements OnInit {
private readonly _destroying$ = new Subject<void>();
constructor(private authService: MsalService, private msalBroadcastService: MsalBroadcastService) { }
ngOnInit(): void {
this.msalBroadcastService.msalSubject$
.pipe(
filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
takeUntil(this._destroying$)
)
.subscribe((result: EventMessage) => {
// do something with the result, such as accessing ID token
});
}
ngOnDestroy(): void {
this._destroying$.next(undefined);
this._destroying$.complete();
}
}
For more information, see: Events in MSAL Angular v2.
Deploying SPA to Azure Storage
There is one single-page application in this sample. To deploy it to Azure Storage, you'll need to:
- create an Azure Storage blob and obtain website coordinates
- build your project and upload it to Azure Storage blob
- update config files with website coordinates
ℹ️ If you would like to use VS Code Azure Tools extension for deployment, watch the tutorial offered by Microsoft Docs.
Build and upload (ciam-msal-angular-spa) to an Azure Storage blob
Build your project to get a distributable files folder, where your built html
, css
and javascript
files will be generated. Then follow the steps below:
⚠️ When uploading, make sure you upload the contents of your distributable files folder and not the entire folder itself.
ℹ️ If you don't have an account already, see: How to create a storage account.
- Sign in to the Microsoft Entra admin center.
- Locate your storage account and display the account overview.
- Select Static website to display the configuration page for static websites.
- Select Enabled to enable static website hosting for the storage account.
- In the Index document name field, specify a default index page (For example:
index.html
). - The default index page is displayed when a user navigates to the root of your static website.
- Select Save. The Microsoft Entra admin center now displays your static website endpoint. Make a note of the Primary endpoint field.
- In the
ciam-msal-angular-spa
project source code, update your configuration file with the Primary endpoint field as your new Redirect URI (you will register this URI later). - Next, select Storage Explorer.
- Expand the BLOB CONTAINERS node, and then select the
$web
container. - Choose the Upload button to upload files.
- If you intend for the browser to display the contents of file, make sure that the content type of that file is set to
text/html
. - In the pane that appears beside the account overview page of your storage account, select Static Website. The URL of your site appears in the Primary endpoint field. In the next section, you will register this URI.
Update the CIAM app registration for ciam-msal-angular-spa
- Navigate back to to the Microsoft Entra admin center.
- In the left-hand navigation pane, select the Microsoft Entra service, and then select App registrations.
- In the resulting screen, select
ciam-msal-angular-spa
. - In the app's registration screen, select Authentication in the menu.
- In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
https://ciam-msal-angular-spa.azurewebsites.net/
- In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
Contributing
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Learn More
- Configure your company branding
- OAuth 2.0 authorization with Microsoft Entra ID
- Language customization in Microsoft Entra External ID
- Building Zero Trust ready apps
- Initialize client applications using MSAL.js
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Pass custom state in authentication requests using MSAL.js
- Prompt behavior in MSAL.js interactive requests
- Use the Microsoft Authentication Library for JavaScript to work with Azure AD B2C