Giter VIP home page Giter VIP logo

microsoft-authentication-library-for-js's Introduction

Microsoft Authentication Library Preview for JavaScript (MSAL.js)

Getting Started Docs Library Reference Support Samples

The MSAL library preview for JavaScript enables client-side JavaScript web applications running in a web browser to authenticate users using Azure AD work and school accounts (AAD), Microsoft personal accounts (MSA) and social identity providers like Facebook, Google, LinkedIn, Microsoft accounts, etc. through Azure AD B2C service. It also enables your app to get tokens to access Microsoft Cloud services such as Microsoft Graph.

Build Statusnpm versionnpm version

Important Note about the MSAL Preview

The MSAL.js core 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 msal

Via CDN:

<!-- Latest compiled and minified JavaScript -->
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.min.js"></script>

Note that msal.js is built for ES5, therefore enabling support for Internet Explorer 11. If you want to target Internet Explorer, you'll need to add a reference to promises polyfill.

<!-- IE support: add promises polyfill before msal.js  -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js" class="pre"></script>

See here for more details on supported browsers.

Usage

The example snippets below show how to acquire a token for Microsoft Graph.

Prerequisite

Before using MSAL.js, register an application in Azure AD to get your clientID.

1. Instantiate the UserAgentApplication

Instantiate the UserAgentApplication with a minimal required configuration of clientID.

A callback function must be passed in for the redirect flows(loginRedirect and acquireTokenRedirect). This 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 promises.

UserAgentApplication has other optional parameters like redirectUri which can be assigned. Please refer to the Wiki to see the full list and their default values.

    var applicationConfig = {
        clientID: 'your_client_id'
    };

     var userAgentApplication = new Msal.UserAgentApplication(applicationConfig.clientID, null, tokenReceivedCallback);

    //callback function for redirect flows
    function tokenReceivedCallback(errorDesc, token, error, tokenType) {
        if (token) {
        }
        else {
            log(error + ":" + errorDesc);
        }
    }

2. Login the user

Your app must login the user with either loginPopup or the loginRedirect method to establish user context. When the login methods are called and the authentication of the user is completed by the Azure AD service, an id token is returned which is used to identify the user with some basic information.

   var graphScopes = ["user.read", "mail.send"];

   userAgentApplication.loginPopup(graphScopes).then(function (idToken) {
       //login success
   }, function (error) {
       //login failure
       console.log(error);
   });

Note: The scopes passed to the login method are optional. In this example, the graphScopes are passed in the login method to obtain consent upfront from the user for your app to access certain Graph API scopes. The idtoken returned here does not contain the scopes. In the next step, you can see how to get an access token which will contain the consented scopes.

3. 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) to Azure AD to obtain an access token. The Azure AD service then returns an access token containing the user consented scopes to allow your app to securely call the API.

If the silent token acquisition fails for some reasons such as an expired token or password change, you will need to invoke an interactive method to acquire tokens such as acquireTokenPopup or acquireTokenRedirect.

   var graphScopes = ["user.read", "mail.send"];

   userAgentApplication.loginPopup(graphScopes).then(function (idToken) {
       //Login Success
       userAgentApplication.acquireTokenSilent(graphScopes).then(function (accessToken) {
           //AcquireTokenSilent Success
       }, function (error) {
           //AcquireTokenSilent Failure, send an interactive request.
           userAgentApplication.acquireTokenPopup(graphScopes).then(function (accessToken) {
               updateUI();
           }, function (error) {
               console.log(error);
           });
       })
   }, function (error) {
       //login failure
       console.log(error);
   });

4. Use the token as a bearer in an HTTP request to call the Microsoft Graph or a Web API

    var headers = new Headers();
    var bearer = "Bearer " + token;
    headers.append("Authorization", bearer);
    var options = {
         method: "GET",
         headers: headers
    };
    var graphEndpoint = "https://graph.microsoft.com/v1.0/me";

    fetch(graphEndpoint, options)
        .then(function (response) {
             //do something with response
        }

You can learn further details about MSAL.js functionality documented in the MSAL Wiki and find complete code samples.

Wrapper libraries

We provide preview versions of the following wrapper libraries as separate packages.

Please check the Roadmap for details on release plans.

Community Help and Support

  • FAQs for access to our frequently asked questions

  • Stack Overflow using "msal" and "msal.js" tag.

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

Contribute

We enthusiastically welcome contributions and feedback. Please read the contributing guide before you begin.

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 [email protected] 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.

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 [email protected] with any additional questions or comments.

microsoft-authentication-library-for-js's People

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.