Skip to content

Latest commit

 

History

History
336 lines (236 loc) · 16.9 KB

File metadata and controls

336 lines (236 loc) · 16.9 KB

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

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. About the code
  10. More information
  11. Community Help and Support
  12. Contributing

Overview

This sample demonstrates an Angular single-page application (SPA) that lets users sign-in with Azure AD B2C using the Microsoft Authentication Library for Angular (MSAL Angular).

Here you'll learn about ID Tokens, OIDC Scopes, external identity providers, consumer social accounts, single-sign on (SSO), silent requests and more.

Scenario

  1. The client Angular SPA uses MSAL Angular to obtain an ID Token from Azure AD B2C.
  2. The ID Token proves that the user has successfully authenticated against Azure AD B2C.

Overview

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

Setup

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 ms-identity-javascript-angular-tutorial
    cd 1-Authentication/2-sign-in-b2c/SPA
    npm install

Registration

⚠️ This sample comes with a pre-registered application for demo purposes. If you would like to use your own Azure AD B2C tenant and application, follow the steps below to register and configure the application on Azure portal. Otherwise, continue with the steps for Running the sample.

Choose the Azure AD tenant where you want to create your applications

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 Azure AD B2C 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 Azure AD B2C tenant.

Create User Flows and Custom Policies

Please refer to: Tutorial: Create user flows in Azure Active Directory B2C

Add External Identity Providers

Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C

Register the app (msal-angular-spa)

  1. Navigate to the Azure portal and select the Azure AD B2C 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:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-angular-spa.
    • Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows).
    • In the Redirect URI section, select Single-page application in the combo-box and enter the following redirect URI: http://localhost:4200.
  4. Select Register to create the application.
  5. In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  6. Select Save to save your changes.

Configure the app (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 clientId and replace the existing value with the application ID (clientId) of msal-react-spa app copied from the Azure portal.

To setup your B2C user-flows, do the following:

  1. Find the key names and populate it with your policy names e.g. signUpSignIn.
  2. Find the key authorities and populate it with your policy authority strings e.g. https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/b2c_1_susi.
  3. Find the key authorityDomain and populate it with the domain portion of your authority string e.g. <your-tenant-name>.b2clogin.com.

Running the sample

    cd 1-Authentication/2-sign-in-b2c/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.

ℹ️ if you believe your issue is with the B2C service itself rather than with the sample, please file a support ticket with the B2C team by following the instructions here.

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

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 APIs: 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();
        }
      });
  }
}

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. See for more: Send a sign-out request.

The sign-out clears the user's single sign-on session with Azure AD B2C, but it might not sign the user out of their social identity provider session. If the user selects the same identity provider during a subsequent sign-in, they might re-authenticate without entering their credentials. Here the assumption is that, if a user wants to sign out of the application, it doesn't necessarily mean they want to sign out of their social account (e.g. Facebook) itself.

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.

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.

Integrating user-flows

  • Sign-up/sign-in

This user-flow allows your users to sign-in to your application if the user has an account already, or sign-up for an account if not. This is the default user-flow that we pass during the initialization of MSAL instance.

  • Edit Profile

When a user selects the Edit Profile button on the navigation bar, we simply initiate a sign-in flow:

  editProfile() {
    let editProfileFlowRequest = {
      scopes: ["openid"],
      authority: b2cPolicies.authorities.editProfile.authority,
    };

    this.login(editProfileFlowRequest);
  }

Like password reset, edit profile user-flow requires users to sign-out and sign-in again.

Next Tutorial

Continue with the next tutorial: Protect and call a web API.

More information

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

Community Help and Support

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. Make sure that your questions or comments are tagged with [azure-active-directory azure-ad-b2c ms-identity adal msal].

If you find a bug in the sample, raise the issue on GitHub Issues.

To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.

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.