Convert Figma logo to code with AI

AzureAD logomicrosoft-authentication-library-for-js

Microsoft Authentication Library (MSAL) for JS

4,102
2,721
4,102
204

Top Related Projects

Auth0 authentication for Single Page Applications (SPA) with PKCE

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes

OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications

23,536

Simple, unobtrusive authentication for Node.js.

Quick Overview

The Microsoft Authentication Library for JavaScript (MSAL.js) is an open-source library that enables developers to authenticate users with Microsoft Azure Active Directory (Azure AD), Microsoft personal accounts, and social identity providers like Facebook, Google, and LinkedIn. It provides a robust set of tools for implementing authentication and authorization in web applications, mobile apps, and desktop applications using JavaScript.

Pros

  • Seamless integration with Microsoft identity platforms and services
  • Support for various authentication flows (e.g., OAuth 2.0, OpenID Connect)
  • Cross-platform compatibility (works in browsers, Node.js, and React Native)
  • Active development and maintenance by Microsoft

Cons

  • Learning curve for developers new to OAuth 2.0 and OpenID Connect
  • Configuration complexity for some advanced scenarios
  • Limited support for non-Microsoft identity providers
  • Potential performance impact in large-scale applications

Code Examples

  1. Initializing MSAL in a browser application:
import { PublicClientApplication } from "@azure/msal-browser";

const msalConfig = {
    auth: {
        clientId: "your_client_id",
        authority: "https://login.microsoftonline.com/your_tenant_id"
    }
};

const msalInstance = new PublicClientApplication(msalConfig);
  1. Acquiring an access token:
const loginRequest = {
    scopes: ["user.read"]
};

msalInstance.loginPopup(loginRequest)
    .then(response => {
        const accessToken = response.accessToken;
        // Use the access token to make API calls
    })
    .catch(error => {
        console.error(error);
    });
  1. Making an authenticated API call:
const apiConfig = {
    uri: "https://graph.microsoft.com/v1.0/me",
    scopes: ["user.read"]
};

msalInstance.acquireTokenSilent(apiConfig)
    .then(response => {
        const headers = new Headers();
        headers.append("Authorization", `Bearer ${response.accessToken}`);

        fetch(apiConfig.uri, { headers })
            .then(response => response.json())
            .then(data => console.log(data));
    })
    .catch(error => {
        console.error(error);
    });

Getting Started

  1. Install MSAL.js using npm:

    npm install @azure/msal-browser
    
  2. Configure MSAL with your Azure AD app registration details:

    const msalConfig = {
        auth: {
            clientId: "your_client_id",
            authority: "https://login.microsoftonline.com/your_tenant_id"
        }
    };
    const msalInstance = new PublicClientApplication(msalConfig);
    
  3. Implement login and token acquisition:

    msalInstance.loginPopup()
        .then(response => {
            console.log("User logged in successfully");
            return msalInstance.acquireTokenSilent({ scopes: ["user.read"] });
        })
        .then(response => {
            console.log("Access token acquired:", response.accessToken);
        })
        .catch(error => {
            console.error(error);
        });
    

Competitor Comparisons

Auth0 authentication for Single Page Applications (SPA) with PKCE

Error generating comparison

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes

Pros of openid-client

  • More comprehensive OpenID Connect support, including advanced features like dynamic client registration
  • Lightweight and flexible, with fewer dependencies
  • Supports a wider range of OpenID providers beyond just Azure AD

Cons of openid-client

  • Less Azure AD-specific optimizations and features
  • May require more configuration and setup for Azure AD scenarios
  • Smaller community and ecosystem compared to MSAL.js

Code Comparison

microsoft-authentication-library-for-js:

const msalConfig = {
    auth: {
        clientId: "your_client_id",
        authority: "https://login.microsoftonline.com/your_tenant_id"
    }
};
const msalInstance = new msal.PublicClientApplication(msalConfig);

openid-client:

const client = await Issuer.discover('https://login.microsoftonline.com/your_tenant_id/v2.0')
    .then(issuer => new issuer.Client({
        client_id: 'your_client_id',
        redirect_uris: ['http://localhost:3000/cb'],
        response_types: ['code']
    }));

Both libraries provide authentication functionality, but microsoft-authentication-library-for-js is more tailored for Azure AD, while openid-client offers a more generic OpenID Connect implementation. The choice between them depends on specific project requirements and the desired level of Azure AD integration.

OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications

Pros of identity-model-oidc-client-js

  • More flexible and protocol-agnostic, supporting a wider range of OIDC and OAuth 2.0 providers
  • Lighter weight and less opinionated, allowing for more customization
  • Better suited for non-Microsoft identity providers and custom OIDC implementations

Cons of identity-model-oidc-client-js

  • Less integrated with Azure AD and Microsoft-specific features
  • Smaller community and potentially less frequent updates
  • May require more configuration and setup for Microsoft-centric scenarios

Code Comparison

microsoft-authentication-library-for-js:

const msalConfig = {
    auth: {
        clientId: "your_client_id",
        authority: "https://login.microsoftonline.com/your_tenant_id"
    }
};
const msalInstance = new msal.PublicClientApplication(msalConfig);

identity-model-oidc-client-js:

const oidcConfig = {
    authority: "https://your-oidc-provider.com",
    client_id: "your_client_id",
    redirect_uri: "your_redirect_uri"
};
const oidcClient = new Oidc.UserManager(oidcConfig);

Both libraries provide similar functionality for authentication, but microsoft-authentication-library-for-js is more tailored for Microsoft Azure AD scenarios, while identity-model-oidc-client-js offers a more generic approach suitable for various OIDC providers. The choice between them depends on the specific requirements of your project and the identity provider you're working with.

23,536

Simple, unobtrusive authentication for Node.js.

Pros of Passport

  • Flexible and modular authentication middleware for Node.js
  • Supports a wide range of authentication strategies (500+ strategies)
  • Integrates easily with various web frameworks and databases

Cons of Passport

  • Requires more setup and configuration compared to MSAL.js
  • Less specialized for Microsoft-specific authentication scenarios
  • May require additional plugins for certain advanced features

Code Comparison

Passport (Express.js example):

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
  function(username, password, done) {
    // Authentication logic here
  }
));

MSAL.js (Browser example):

const msalConfig = {
  auth: {
    clientId: "your_client_id",
    authority: "https://login.microsoftonline.com/your_tenant_id"
  }
};
const msalInstance = new msal.PublicClientApplication(msalConfig);

Passport offers a more generic approach to authentication, supporting various strategies and integrating well with different frameworks. MSAL.js, on the other hand, is specifically designed for Microsoft authentication scenarios, providing a more streamlined experience for Azure AD and Microsoft identity platform integration.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Microsoft Authentication Library for JavaScript (MSAL.js)

The Microsoft Authentication Library for JavaScript enables both client-side and server-side JavaScript applications to authenticate users using Microsoft Entra ID for work and school accounts, 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.

Repository

Core, wrapper and extensions libraries

The lib folder contains the source code for our libraries in active development. You will also find all the details about installing the libraries in their respective README.md.

Library Version Support Status

Package NameCurrent VersionLTS Version
@azure/msal-browserv5v4
@azure/msal-nodev5v3
@azure/msal-reactv5v3
@azure/msal-angularv5v4
@azure/msal-node-extensionsv5v1
@azure/msal (msal-core)Fully Deprecated
@azure/msal-angularjsFully Deprecated

Disambiguation:

  • The MSAL team provides full support to the current version for each package in the table below.
  • LTS (long-term support) versions will still receive some support and critical bug-fixes but will not ship new features. Our recommendation if you encounter any issues will always be to upgrade to the latest version of the library.
  • All supported packages were brought up to version parity as of v5. Packages with versions lower than v4 in the LTS column skipped as many versions as required to jump directly to v5.

MSAL Browser CDN Deprecation

:warning: The @azure/msal-browser CDN has been fully deprecated as of @azure/msal-browser@3.0.0 and is no longer supported. App developers using the MSAL CDN must upgrade to the latest possible version and consume MSAL through a package manager or bundling tool of their choice. For more information on version support, consult the table above.

Package Structure

We ship a number of different packages which are meant for different platforms. You can see the relationship between packages and their dependencies below.

Package Structure

Samples

The samples folder contains sample applications for our libraries. A complete list of samples can be found in the respective package folders.

Package versioning

All of our libraries follow semantic versioning. We recommend using the latest version of each library to ensure you have the latest security patches and bug fixes.

Community Help and Support

  • GitHub Issues is the best place to ask questions, report bugs, and new request features.

  • FAQs for access to our frequently asked questions.

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

Contribute

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

Security Reporting

If you find a security issue with our libraries or services please report it to the Microsoft Security Response Center (MSRC) 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 opencode@microsoft.com with any additional questions or comments.

NPM DownloadsLast 30 Days