msx-silent
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

Multitarget version of Microsoft Authentication Library Preview for JavaScript

Update: For Use in Teams Tab App..Silent Token retrieval without iFrame and Teams Popup:

userAgentApplication.acquireTokenSilent(scopes)
  // Or however you want to catch this..
  .catch(e => ({error: e}));
//If you catch an error..then call msteams for interactive login
microsoftTeams.authentication.authenticate(authParams)

Msal.js is in preview and does not support CommonJS or ES6 targets. This is a temporary solution to be used in react projects until the original repository supports CommonJS.

Getting Started Docs API Reference Support Samples

The MSAL library preview for JavaScript enables your app to authorize enterprise users using Microsoft Azure Active Directory (AAD), Microsoft account users (MSA), users using social identity providers like Facebook, Google, LinkedIn etc. and get access to Microsoft Cloud OR Microsoft Graph.

The identity management services that the library interacts with are Microsoft Azure Active Directory, Microsoft Azure B2C and Microsoft Accounts.

npm version npm version

Important Note about the MSAL Preview

This library is suitable for use in a production environment. We provide the same production level support for this library as we do our current production libraries. During the preview we may make changes to the API, internal cache format, and other mechanisms of this library, which you will be required to take along with bug fixes or feature improvements. This may impact your application. For instance, a change to the cache format may impact your users, such as requiring them to sign in again. An API change may require you to update your code. When we provide the General Availability release we will require you to update to the General Availability version within six months, as applications written using a preview version of library may no longer work.

Installation

Via NPM: npm install msalx-slient

Example

This example shows how to acquire a token to read user information from Microsoft Graph.

  1. Register an application in Azure AD v2.0 (using the application registration portal) to get your client_id. you will also need to add the Web platform, check the "Implicit Flow" checkbox, and add the redirectURI to your application.
  2. Instantiate a UserAgentApplication and login the user:
import * as React from 'react';
import { render } from 'react-dom';
import { UserAgentApplication } from 'msalx';

var applicationConfig = {
  clientID: 'e760cab2-b9a1-4c0d-86fb-ff7084abd902',
  authority: "https://login.microsoftonline.com/tfp/fabrikamb2c.onmicrosoft.com/b2c_1_susi",
  b2cScopes: ["https://fabrikamb2c.onmicrosoft.com/demoapi/demo.read"],
  webApi: 'https://fabrikamb2chello.azurewebsites.net/hello',
};

class App extends React.Component<{}, { isLoggedIn: boolean, message: string }> {
  
  clientApplication = new UserAgentApplication(applicationConfig.clientID, applicationConfig.authority,
    (errorDesc, token, error, tokenType) => {
      // Called after loginRedirect or acquireTokenPopup
      if (tokenType == "id_token") {
        var userName = this.clientApplication.getUser().name;
        this.setState({ isLoggedIn: true });
        this.logMessage("User '" + userName + "' logged-in");
      } else {
        this.logMessage("Error during login:\n" + error);
      }
    });

  state = {
    isLoggedIn: false,
    message: ""
  }

  logMessage(message: string) {
    this.setState({ message: this.state.message + "\n" + message });
  }

  loginRedirect() {
    this.clientApplication.loginRedirect(applicationConfig.b2cScopes);
  }

  logout() {
    this.clientApplication.logout();
  }
  
  loginPopup() {
    this.clientApplication.loginPopup(applicationConfig.b2cScopes).then((idToken) => {
      this.clientApplication.acquireTokenSilent(applicationConfig.b2cScopes).then((accessToken) => {
        var userName = this.clientApplication.getUser().name;
        this.setState({ isLoggedIn: true });
        this.logMessage("User '" + userName + "' logged-in");
      }, (error) => {
        this.clientApplication.acquireTokenPopup(applicationConfig.b2cScopes).then((accessToken) => {
          var userName = this.clientApplication.getUser().name;
          this.setState({ isLoggedIn: true });
          this.logMessage("User '" + userName + "' logged-in");
        }, (error) => {
          this.logMessage("Error acquiring the popup:\n" + error);
        });
      })
    }, (error) => {
      this.logMessage("Error during login:\n" + error);
    });
  }

  callApi() {
    this.clientApplication.acquireTokenSilent(applicationConfig.b2cScopes).then((accessToken) => {
      this.callApiWithAccessToken(accessToken);
    }, (error) => {
      this.clientApplication.acquireTokenPopup(applicationConfig.b2cScopes).then((accessToken) => {
        this.callApiWithAccessToken(accessToken);
      }, (error) => {
        this.logMessage("Error acquiring the access token to call the Web api:\n" + error);
      });
    })
  }

  callApiWithAccessToken(accessToken: string) {
    // Call the Web API with the AccessToken
    fetch(applicationConfig.webApi, {
      method: "GET",
      headers: { 'Authorization': 'Bearer ' + accessToken }
    }).then(response => {
      response.text().then(text => this.logMessage("Web APi returned:\n" + JSON.stringify(text)));
    }).catch(result => {
      this.logMessage("Error calling the Web api:\n" + result);
    });
  }

  render() {
    return (
      <div style={{ width: '900px', margin: 'auto' }}>
        <h1>Hello World!</h1>
        <button onClick={() => this.loginPopup()} disabled={this.state.isLoggedIn}>Login Popup</button>
        <button onClick={() => this.loginRedirect()} disabled={this.state.isLoggedIn}>Login Redirect</button>
        <button onClick={() => this.logout()} disabled={!this.state.isLoggedIn}>Logout</button>
        <button onClick={() => this.callApi()} disabled={!this.state.isLoggedIn}>Call Web API</button>
        <pre>{this.state.message}</pre>
      </div>
    );
  }
}

render(<App />, document.getElementById('root') as HTMLElement);

Community Help and Support

  • FAQ for access to our frequently asked questions

  • Stack Overflow using tag MSAL. We highly recommend you ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.

  • GitHub Issues for reporting an bug or feature requests

  • User Voice page to provide recommendations and/or feedback

Contribute

We enthusiastically welcome contributions and feedback. You can clone the repo and start contributing now. Read our Contribution Guide for more information.

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.

Security Library

This library controls how users sign-in and access services. We recommend you always take the latest version of our library in your app when possible. We use semantic versioning so you can control the risk associated with updating your app. As an example, always downloading the latest minor version number (e.g. x.y.x) ensures you get the latest security and feature enhanements but our API surface remains the same. You can always see the latest version and release notes under the Releases tab of GitHub.

Security Reporting

If you find a security issue with our libraries or services please report it to secure@microsoft.com with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");

License

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");

We Value and Adhere to the Microsoft Open Source Code of Conduct

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.

Readme

Keywords

none

Package Sidebar

Install

npm i msx-silent

Weekly Downloads

0

Version

0.1.2

License

MIT

Last publish

Collaborators

  • samwomack