Skip to content

Latest commit

 

History

History
415 lines (306 loc) · 22.5 KB

File metadata and controls

415 lines (306 loc) · 22.5 KB
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)
javascript
typescript
entra-external-id
msal-angular
ms-identity-ciam-javascript-tutorial-2-sign-in-angular
services platform endpoint level client
ms-identity
JavaScript
AAD v2.0
100
Angular SPA

Angular single-page application using MSAL Angular to sign-in users against Azure AD for Customers

Overview

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

Scenario

  1. The client Angular SPA uses the to sign-in a user and obtain a JWT ID Token from Azure AD for Customers.
  2. The ID Token proves that the user has successfully authenticated against Azure AD for Customers.

Scenario Image

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

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.

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 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.

Choose the CIAM tenant where you want to create your applications

To manually register the apps, as a first step you'll need to:

  1. Sign in to the Azure portal.
  2. 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.

Create User Flows

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

Add External Identity Providers

Please refer to:

Register the spa app (ciam-msal-angular-spa)

  1. Navigate to the Azure portal and select the CIAM service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. In the Register an application page that appears, enter your application's registration information:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example ciam-msal-angular-spa.
    2. Under Supported account types, select Accounts in this organizational directory only
    3. Select Register to create the application.
  4. 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.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Single-page application option.
    1. In the Redirect URI section enter the following redirect URI:
      1. http://localhost:4200
    2. Click Save to save your changes.
  7. Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
    1. 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:
    2. Select the Add a permission button and then:
    3. Ensure that the Microsoft APIs tab is selected.
    4. In the Commonly used Microsoft APIs section, select Microsoft Graph
    5. In the Delegated permissions section, select openid, offline_access in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.
  8. 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.
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".

  1. Open the SPA\src\app\auth-config.ts file.
  2. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of ciam-msal-angular-spa app copied from the Azure portal.
  3. Find the placeholder Enter_the_Tenant_Subdomain_Here and replace it with the Directory (tenant) subdomain. For instance, if your tenant primary domain is contoso.onmicrosoft.com, use contoso. 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

  1. Open your browser and navigate to http://localhost:4200.
  2. 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.

Screenshot

ℹ️ 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 Azure Active Directory, 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.

  1. The callback is registered only once
  2. 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.

  1. Sign in to the Azure portal.
  2. Locate your storage account and display the account overview.
  3. Select Static website to display the configuration page for static websites.
  4. Select Enabled to enable static website hosting for the storage account.
  5. In the Index document name field, specify a default index page (For example: index.html).
  6. The default index page is displayed when a user navigates to the root of your static website.
  7. Select Save. The Azure portal now displays your static website endpoint. Make a note of the Primary endpoint field.
  8. 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).
  9. Next, select Storage Explorer.
  10. Expand the BLOB CONTAINERS node, and then select the $web container.
  11. Choose the Upload button to upload files.
  12. 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.
  13. 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

  1. Navigate back to to the Azure portal.
  2. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations.
  3. In the resulting screen, select ciam-msal-angular-spa.
  4. In the app's registration screen, select Authentication in the menu.
    1. In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
      1. https://ciam-msal-angular-spa.azurewebsites.net/

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