msal_js 1.2.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 68

MSAL.js for Dart #

A Dart wrapper for the Microsoft Authentication Library for JavaScript (MSAL.js).

Contents #

Install msal.js #

This package does not come with msal.js. Please refer to the msal.js documentation for installation.

See the msal.js support table below to determine which version of msal.js should be used with each version of this package.

Usage #

See example/ for a more complete example.

Also see the msal.js documentation. Class, function, and parameter names are almost all the same between this wrapper and msal.js (please see "Differences from msal.js" for more information). Following msal.js examples should be mostly straight-forward.

Short getting started example:

import 'package:msal_js/msal_js.dart';

void main() {
  // Important note about the below 'options' objects:
  // To set an option to `undefined`, simply don't call
  // the setter for that option at all. This will let
  // msal.js use the option's default value. Setting an
  // option to `null` will not use its default value.

  // Create an MSAL logger (optional)
  var logger = new Logger(_loggerCallback,
    new LoggerOptions()
      ..level = LogLevel.verbose // log everything

  // Configure and create an MSAL authentication context
  // Note: Only clientId is required
  var config = new Configuration()
    ..auth = (new AuthOptions()
      ..clientId = 'your_client_id'

  var userAgentApplication = new UserAgentApplication(config);

  // If you plan on using the redirect flow, register a callback

  // Login by calling either:
  // - userAgentApplication.loginRedirect
  // - userAgentApplication.loginPopup

  // After login, acquire an access token by calling:
  // userAgentApplication.acquireTokenSilent

  // If acquiring the token silently fails, use either:
  // - userAgentApplication.acquireTokenRedirect
  // - userAgentApplication.acquireTokenPopup

  // See the msal.js documentation for more information.

void _loggerCallback(LogLevel level, String message, bool containsPii) {
  print('[$level] $message');

void _authCallback(AuthException error, [AuthResponse response]) {
  // ...

Differences from msal.js #

This package has a few minor differences from the JavaScript and TypeScript APIs in msal.js. These are mainly due to incompatibilities between TypeScript and Dart and quality-of-life differences to provide a more idiomatic Dart API.

  • APIs returning JavaScript Promises instead return Dart Futures.
  • TypeScript string unions (such as cacheLocation) are represented as Dart enums.
  • MSAL errors are represented as Dart exceptions and use the suffix Exception instead of Error (e.g. AuthError in msal.js is AuthException in this wrapper).
  • Typescript interfaces are represented as a full Dart type. Instead of passing a map which meets the interface requirements, an actual type must be constructed (e.g. instead of loginPopup({scopes: []}) you would do loginPopup(new AuthRequest()..scopes = [])).

msal.js Support Table #

Each package version (on the left) specifies which version of msal.js it supports (on the right). Only changes in support are added to this table.

If the package version you are looking for is not listed, use the row corresponding to the next listed version going down. For example, the package version 0.3.0 is not listed, so the version of msal.js that 0.3.0 supports is 0.2.3 since the next package entry down is 0.2.0 (which supports msal.js 0.2.3).


v1.2.1 #

  • Fix acquireTokenPopup, acquireTokenSilent, and loginPopup failing to correctly convert JS promise errors to exceptions.

v1.2.0 #

  • Support for msal.js v1.2.x
  • Added AuthRequest.redirectUri

v1.1.0 #

  • Support for msal.js v1.1.x
  • Added Account.idTokenClaims
  • Added AuthRequest.forceRefresh

v1.0.1 #

  • Fixed AuthRequest.extraQueryParameters not working.
  • Removed dependency on package:js.
  • Deprecated FrameworkOptions. The 'framework' configuration for UserAgentApplication is an unfortunate coupling between msal-core and msal-angular(js). Since this package only wraps msal-core, setting these options does nothing and should not have been included in the API to begin with. It will be removed in a future release.

v1.0.0 #

See for conceptual breaking changes in 1.0.

  • Support for msal.js v1.0.x.
  • Changed minimum Dart SDK version from 1.23.0 to 2.0.0.
  • Replaced User with Account.
  • Replaced MsalException with AuthException and its inheritors.
  • UserAgentApplication changes:
    • Login/acquire methods now take in and return AuthRequest and AuthResponse respectively.
    • Constructor now takes in a single Configuration object.
    • Replaced TokenReceivedCallback with AuthResponseCallback.
    • Replaced getUser with getAccount.
    • Replaced getAllUsers with getAllAccounts.
    • Replaced loginInProgress with getLoginInProgress.
    • Added handleRedirectCallback.
    • Added getCurrentConfiguration.
    • Added getPostLogoutRedirectUri.
    • Added getRedirectUri.
    • Removed cacheLocation.
    • Removed loadFrameTimeout.
    • Removed clientId.
    • Removed validateAuthority.
  • Added missing getters to LoggerOptions.
  • Fixed error when providing null for options when creating a Logger.

v0.3.2 #

  • Support for msal.js v0.2.4.
  • UserAgentApplicationOptions changes:
    • redirectUri may now be either a String or RedirectUriCallback.
    • postLogoutRedirectUri may now be either a String or RedirectUriCallback.
  • UserAgentApplication changes:
    • The constructor parameter tokenReceivedCallback may now be null.

v0.3.1 #

  • Fix crash which occurred when using the logger callback in code compiled with dart2js.

v0.3.0 #

  • Rewrote entire library using package:js.
  • The constructor for UserAgentApplication now semantically matches the JavaScript version.
  • The constructor for Logger now semantically matches the JavaScript version.
  • No longer contains a build of msal.js. A valid version of msal.js must be installed separately.

Versions listed below are not available on pub as they were made before this package was published.

v0.2.1 #

  • Fix MsalException not correctly decoding the error code/description.

v0.2.0 #

  • Support for msal.js v0.2.3.
  • All UserAgentApplication constructor parameters are now named. Parameters that used to be positional are now marked as @required.

v0.1.0 #

  • Support for msal.js v0.1.5.



This example is based on

Only information related to library usage is present in this file, it is highly recommended to read the MSAL.js version first as it also covers Azure AD concepts related to the library.

This example is just meant to cover the translation of the example from JavaScript to Dart.

Contents #

  1. Instantiate the UserAgentApplication
  2. Login the user
  3. Get an access token to call an API
  4. Use the token as a bearer in an HTTP request

Instantiate the UserAgentApplication #

UserAgentApplication can be configured with a variety of different options, but only auth.clientId is required.

After instantiating your instance, if you plan on using a redirect flow (loginRedirect and acquireTokenRedirect), you must register a callback handlers using handleRedirectCallback. The callback function is called after the authentication request is completed either successfully or with a failure. This is not required for the popup flows since they return futures.

// Import msal_js
import 'package:msal_js/msal_js.dart';

// Configure and create the UserAgentApplication
final config = new Configuration()
  ..auth = (new AuthOptions()
    ..clientId = 'your_client_id'

final userAgentApplication = new UserAgentApplication(config);

// Register a callback for redirect flows (optional)

void authCallback(AuthException error, [AuthResponse response]) {
  // handle redirect response or error

Login the user #

Your app must login the user with either the loginPopup or the loginRedirect method to establish the user context.

// Login via popup example
final loginRequest = new AuthRequest()
  ..scopes = ['', 'mail.send'];

try {
  final AuthResponse response = 
    await userAgentApplication.loginPopup(loginRequest);

  // Handle successful response
} on AuthException catch (ex) {
  // Handle error

Get an access token to call an API #

In MSAL, you can get access tokens for the APIs your app needs to call using the acquireTokenSilent method which makes a silent request (without prompting the user with UI) to Azure AD to obtain an access token.

You can use acquireTokenRedirect or acquireTokenPopup to initiate interactive requests, although, it is best practice to only show interactive experiences if you are unable to obtain a token silently due to interaction required errors. If you are using an interactive token call, it must match the login method used in your application. (loginPopup => acquireTokenPopup, loginRedirect => acquireTokenRedirect).

If the acquireTokenSilent call fails with an error of type InteractionRequiredAuthException you will need to initiate an interactive request. This could happen for many reasons including scopes that have been revoked, expired tokens, or password changes.

acquireTokenSilent will look for a valid token in the cache, and if it is close to expiring or does not exist, will automatically try to refresh it for you.

// If the user is already logged in, you can acquire a token
if (userAgentApplication.getAccount() != null) {
  final tokenRequest = new AuthRequest()
    ..scopes = ['', 'mail.send'];

  try {
    // Try silently
    final AuthResponse response = 
      await userAgentApplication.acquireTokenSilent(tokenRequest);

    // Get access token from response.accessToken
  } on InteractionRequiredAuthException {
    // Interactive prompt is required to get token
    try {
      final AuthResponse response = 
        await userAgentApplication.acquireTokenPopup(tokenRequest);
      // Get access token from response.accessToken
    } on AuthException catch (ex) {
      // Handle error
} else {
  // User is not logged in, you will need to log them in to acquire a token

Use the token as a bearer in an HTTP request #

Simple package:http example of using Microsoft Graph with a token:

import 'package:http/http.dart';

final Client client = new BrowserClient();

final Response response = await client.get(
  headers: {
    'Authorization': 'Bearer $token'

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  msal_js: ^1.2.1

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:msal_js/msal_js.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on Apr 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6

Health suggestions

Format lib/msal_js.dart.

Run dartfmt to format lib/msal_js.dart.

Format lib/src/account.dart.

Run dartfmt to format lib/src/account.dart.

Format lib/src/auth_request.dart.

Run dartfmt to format lib/src/auth_request.dart.

Fix additional 11 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/auth_response.dart (Run dartfmt to format lib/src/auth_response.dart.)
  • lib/src/cache_location.dart (Run dartfmt to format lib/src/cache_location.dart.)
  • lib/src/configuration.dart (Run dartfmt to format lib/src/configuration.dart.)
  • lib/src/exceptions.dart (Run dartfmt to format lib/src/exceptions.dart.)
  • lib/src/logger.dart (Run dartfmt to format lib/src/logger.dart.)
  • lib/src/msal.dart (Run dartfmt to format lib/src/msal.dart.)
  • lib/src/user_agent_application.dart (Run dartfmt to format lib/src/user_agent_application.dart.)
  • lib/src/utils/js_object_as_list.dart (Run dartfmt to format lib/src/utils/js_object_as_list.dart.)
  • lib/src/utils/js_object_as_map.dart (Run dartfmt to format lib/src/utils/js_object_as_map.dart.)
  • lib/src/utils/js_object_converter.dart (Run dartfmt to format lib/src/utils/js_object_converter.dart.)
  • lib/src/utils/promise_utils.dart (Run dartfmt to format lib/src/utils/promise_utils.dart.)


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
Dev dependencies
pedantic 1.8.0
test ^1.9.0