page_type | name | description | languages | products | urlFragment | extensions | |||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
Angular single-page application using MSAL Angular to sign-in users against Azure AD for Customers |
This sample demonstrates an Angular single-page application (SPA) that uses Microsoft Authentication Library for Angular (MSAL Angular) to sign-in users with Azure Active Directory Consumers Identity and Access Management (Azure AD for Customers) |
|
|
ms-identity-ciam-javascript-tutorial-2-sign-in-angular |
|
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Contributing
- Learn More
This sample demonstrates an Angular single-page application (SPA) that lets users sign-in with Azure Active Directory (Azure AD) Consumers Identity and Access Management (CIAM) 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.
ℹ️ To learn how to integrate a JavaScript Angular application with Azure AD,consider going through the recorded session: Deep dive on using MSAL.js to integrate Angular single-page applications with Azure Active Directory
- The client Angular SPA uses the to sign-in a user and obtain a JWT ID Token from Azure AD for Customers.
- The ID Token proves that the user has successfully authenticated against Azure AD for Customers.
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. |
- 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 CIAM tenant. For more information, see: How to get an Azure AD for Customers tenant
- A user account in your CIAM tenant.
This sample will not work with a personal Microsoft account. If you're signed in to the Azure portal with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
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.
cd 1-Authentication\1-sign-in-angular\SPA
npm install
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 Azure AD 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.
To manually register the apps, as a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one CIAM 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 CIAM tenant.
Please refer to: Tutorial: Create user flow in Azure Active Directory CIAM
ℹ️ To enable password reset in Customer Identity Access Management (CIAM) in Azure Active Directory (Azure AD), please refer to: Tutorial: Enable self-service password reset
Please refer to:
- Navigate to the Azure portal 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 a CIAM 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.
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 Azure portal. - 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.
cd 1-Authentication\1-sign-in-angular\SPA
npm start
- 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.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
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 Azure Active Directory, visit User Voice page.
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.
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.
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();
}
});
}
}
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.
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.
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
]
}
]
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.
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 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 Azure portal.
- 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 Azure portal 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.
- Navigate back to to the Azure portal.
- In the left-hand navigation pane, select the Azure Active Directory 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:
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.
- Customize the default branding
- OAuth 2.0 device authorization grant flow
- Customize sign-in strings
- 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 MSAL.js to work with Azure AD B2C