msal_js 1.1.0

  • 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/example.md 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
  userAgentApplication.handleRedirectCallback(_authCallback);

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

Versionmsal.js
1.1.01.1.0
1.0.01.0.0
0.3.20.2.4
0.2.00.2.3
0.1.00.1.5

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 https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL.js-1.0.0-api-release 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.

example/example.md

NOTE: PLEASE READ FIRST

This example is based on https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-core/README.md#usage.

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)
userAgentApplication.handleRedirectCallback(authCallback);

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 = ['user.read', '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 = ['user.read', '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(
  'https://graph.microsoft.com/v1.0/me',
  headers: {
    'Authorization': 'Bearer $token'
  }
);

Use this package as a library

1. Depend on it

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


dependencies:
  msal_js: ^1.1.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

Alternatively, your editor might support 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';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
40
Health:
Code health derived from static analysis. [more]
93
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
68
Learn more about scoring.

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

  • Dart: 2.6.1
  • pana: 0.12.21

Platforms

Detected platforms: web, other

Primary library: package:msal_js/msal_js.dart with components: js.

Health suggestions

Fix lib/src/configuration.dart. (-2.48 points)

Analysis of lib/src/configuration.dart reported 5 hints:

line 35 col 19: Unnecessary new keyword.

line 145 col 19: Unnecessary new keyword.

line 176 col 19: Unnecessary new keyword.

line 212 col 19: Unnecessary new keyword.

line 243 col 19: Unnecessary new keyword.

Fix lib/src/exceptions.dart. (-2.48 points)

Analysis of lib/src/exceptions.dart reported 5 hints:

line 19 col 12: Unnecessary new keyword.

line 21 col 12: Unnecessary new keyword.

line 23 col 12: Unnecessary new keyword.

line 25 col 12: Unnecessary new keyword.

line 27 col 12: Unnecessary new keyword.

Fix lib/src/auth_request.dart. (-0.50 points)

Analysis of lib/src/auth_request.dart reported 1 hint:

line 97 col 21: Unnecessary new keyword.

Fix additional 11 files with analysis or formatting issues. (-1.50 points)

Additional issues in the following files:

  • lib/src/logger.dart (1 hint)
  • lib/src/msal.dart (1 hint)
  • lib/src/utils/promise_utils.dart (1 hint)
  • lib/msal_js.dart (Run dartfmt to format lib/msal_js.dart.)
  • lib/src/account.dart (Run dartfmt to format lib/src/account.dart.)
  • 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/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.)

Dependencies

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