Convert Figma logo to code with AI

AzureAD logomicrosoft-authentication-library-for-js

Microsoft Authentication Library (MSAL) for JS

3,640
2,648
3,640
145

Top Related Projects

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes

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

22,914

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

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 oidc-client-js

  • More lightweight and focused specifically on OpenID Connect (OIDC) protocol
  • Easier to integrate with non-Microsoft identity providers
  • Better support for OIDC features like session management and dynamic client registration

Cons of oidc-client-js

  • Less comprehensive documentation and examples compared to MSAL.js
  • Smaller community and fewer resources for troubleshooting
  • Limited built-in support for Microsoft-specific features and integrations

Code Comparison

oidc-client-js:

const settings = {
  authority: 'https://example.com',
  client_id: 'client_id',
  redirect_uri: 'https://app.example.com/callback'
};
const userManager = new Oidc.UserManager(settings);
userManager.signinRedirect();

microsoft-authentication-library-for-js:

const msalConfig = {
  auth: {
    clientId: 'client_id',
    authority: 'https://login.microsoftonline.com/tenant_id'
  }
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
msalInstance.loginRedirect();

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

22,914

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 Azure AD for 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.

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.

Libraries in Long-term Support (LTS)

The following libraries, hosted on the msal-lts branch, are no longer in active development, but they are still receiving critical security bug fix support.

Package Structure

We ship a number of different packages which are meant for different platforms. You can see the relationship between packages and different authentication flows they implement 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 or on our wiki.

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.

Roadmap

Please check the roadmap to see what we are working on and what we have planned for future releases.

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