Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
The msal (Microsoft Authentication Library) npm package is used to authenticate users and acquire tokens to access protected resources such as Microsoft Graph, other Microsoft APIs, or your own APIs. It supports various authentication flows and can be used in different environments including single-page applications (SPA), server-side applications, and mobile apps.
User Authentication
This code demonstrates how to configure the msal package for user authentication in a Node.js application. It sets up the client application with the necessary credentials and generates an authorization code URL.
const msal = require('@azure/msal-node');
const config = {
auth: {
clientId: 'your_client_id',
authority: 'https://login.microsoftonline.com/your_tenant_id',
clientSecret: 'your_client_secret'
}
};
const cca = new msal.ConfidentialClientApplication(config);
const authCodeUrlParameters = {
scopes: ['user.read'],
redirectUri: 'http://localhost:3000/redirect'
};
cca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
console.log(response);
}).catch((error) => console.log(JSON.stringify(error)));
Token Acquisition
This code demonstrates how to acquire an access token using an authorization code. The access token can then be used to access protected resources.
const tokenRequest = {
code: 'auth_code_received_from_auth_code_url',
scopes: ['user.read'],
redirectUri: 'http://localhost:3000/redirect'
};
cca.acquireTokenByCode(tokenRequest).then((response) => {
console.log('Access token:', response.accessToken);
}).catch((error) => console.log(JSON.stringify(error)));
Silent Token Acquisition
This code demonstrates how to silently acquire an access token for a user who is already signed in, without requiring user interaction.
const silentRequest = {
account: account,
scopes: ['user.read']
};
cca.acquireTokenSilent(silentRequest).then((response) => {
console.log('Access token:', response.accessToken);
}).catch((error) => console.log(JSON.stringify(error)));
The passport-azure-ad package is a collection of Passport strategies to help you integrate with Azure Active Directory. It supports various authentication flows including OpenID Connect, OAuth 2.0, and SAML. Compared to msal, passport-azure-ad is more focused on integrating with the Passport.js middleware for Node.js applications.
The oidc-client package is a JavaScript library for OpenID Connect (OIDC) and OAuth2. It is used for managing user authentication and token management in client-side applications. While msal is specifically designed for Microsoft identity platform, oidc-client is more generic and can be used with any OIDC-compliant identity provider.
The auth0-js package is a client-side library for integrating with Auth0, a popular identity-as-a-service provider. It provides similar functionalities to msal, such as user authentication and token acquisition, but is designed to work with Auth0's identity platform rather than Microsoft's.
Getting Started | AAD Docs | Library Reference | Support | Samples |
---|
⚠️⚠️⚠️ This library is no longer receiving new features and will only receive critical bug and security fixes. All new applications should use @azure/msal-browser instead. ⚠️⚠️⚠️
MSAL 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.
npm install msal
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.17/js/msal.min.js"></script>
Complete details and best practices for CDN usage are available in our documentation.
Msal support on JavaScript is a collection of libraries. msal-core
or just simply msal
, is the framework agnostic core library. Once our core 1.x+ is stabilized, we are going to bring our msal-angular
library with the latest 1.x improvements. We are planning to deprecate support for msal-angularjs
based on usage trends of the framework and the library indicating increased adoption of Angular 2+ instead of Angular 1x. After our current libraries are up to standards, we will begin balancing new feature requests, with new platforms such as react
and node.js
.
Our goal is to communicate extremely well with the community and to take their opinions into account. We would like to get to a monthly minor release schedule, with patches coming as often as needed. The level of communication, planning, and granularity we want to get to will be a work in progress.
Please check our roadmap to see what we are working on and what we are tracking next.
Msal implements the Implicit Grant Flow, as defined by the OAuth 2.0 protocol and is OpenID compliant.
Our goal is that the library abstracts enough of the protocol away so that you can get plug and play authentication, but it is important to know and understand the implicit flow from a security perspective. The implicit flow runs in the context of a web browser which cannot manage client secrets securely. It is optimized for single page apps and has one less hop between client and server so tokens are returned directly to the browser. These aspects make it naturally less secure. These security concerns are mitigated per standard practices such as- use of short lived tokens (and so no refresh tokens are returned), the library requiring a registered redirect URI for the app, library matching the request and response with a unique nonce and state parameter.
We offer two methods of storage for Msal, localStorage
and sessionStorage
. Our recommendation is to use sessionStorage
because it is more secure in storing tokens that are acquired by your users, but localStorage
will give you Single Sign On accross tabs and user sessions. We encourge you to explore the options and make the best decision for your application.
If you would like to skip a cached token and go to the server, please pass in the boolean forceRefresh
into the AuthenticationParameters
object used to make a login / token request. WARNING: This should not be used by default, because of the performance impact on your application. Relying on the cache will give your users a better experience, and skipping it should only be used in scenarios where you know the current cached data does not have up to date information. Example: Admin tool to add roles to a user that needs to get a new token with updates roles.
The example below walks you through how to login a user and acquire a token to be used for Microsoft's Graph Api.
Before using MSAL.js you will need to register an application in Azure AD to get a valid clientId
for configuration, and to register the routes that your app will accept redirect traffic on.
UserAgentApplication
can be configured with a variety of different options, detailed in our Wiki, but the only required parameter is auth.clientId
.
After instantiating your instance, if you plan on using a redirect flow in MSAL 1.2.x or earlier (loginRedirect
and acquireTokenRedirect
), you must register a callback handler using handleRedirectCallback(authCallback)
where authCallback = function(AuthError, AuthResponse)
. As of MSAL 1.3.0 this is optional. 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 promises.
import * as Msal from "msal";
// if using cdn version, 'Msal' will be available in the global scope
const msalConfig = {
auth: {
clientId: 'your_client_id'
}
};
const msalInstance = new Msal.UserAgentApplication(msalConfig);
msalInstance.handleRedirectCallback((error, response) => {
// handle redirect response or error
});
For details on the configuration options, read Initializing client applications with MSAL.js.
Your app must login the user with either the 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.
When you login a user, you can pass in scopes that the user can pre consent to on login, however this is not required. Please note that consenting to scopes on login, does not return an access_token for these scopes, but gives you the opportunity to obtain a token silently with these scopes passed in, with no further interaction from the user.
It is best practice to only request scopes you need when you need them, a concept called dynamic consent. While this can create more interactive consent for users in your application, it also reduces drop-off from users that may be uneasy granting a large list of permissions for features they are not yet using.
AAD will only allow you to get consent for 3 resources at a time, although you can request many scopes within a resource. When the user makes a login request, you can pass in multiple resources and their corresponding scopes because AAD issues an idToken pre consenting those scopes. However acquireToken calls are valid only for one resource / multiple scopes. If you need to access multiple resources, please make separate acquireToken calls per resource.
var loginRequest = {
scopes: ["user.read", "mail.send"] // optional Array<string>
};
msalInstance.loginPopup(loginRequest)
.then(response => {
// handle response
})
.catch(err => {
// handle error
});
If you are confident that the user has an existing session and would like to establish user context without prompting for interaction, you can invoke ssoSilent
with a loginHint
or sid
(available as an optional claim) and MSAL will attempt to silently SSO to the existing session and establish user context.
Note, if there is no active session for the given loginHint
or sid
, an error will be thrown, which should be handled by invoking an interactive login method (loginPopup
or loginRedirect
).
Example:
const ssoRequest = {
loginHint: "user@example.com"
};
msalInstance.ssoSilent(ssoRequest)
.then(response => {
// session silently established
})
.catch(error => {
// handle error by invoking an interactive login method
msalInstance.loginPopup(ssoRequest);
});
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. The Azure AD service then returns an access token containing the user consented scopes to allow your app to securely call the API.
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 InteractionRequiredAuthError
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.
See Request and Response Data Types for reference.
// if the user is already logged in you can acquire a token
if (msalInstance.getAccount()) {
var tokenRequest = {
scopes: ["user.read", "mail.send"]
};
msalInstance.acquireTokenSilent(tokenRequest)
.then(response => {
// get access token from response
// response.accessToken
})
.catch(err => {
// could also check if err instance of InteractionRequiredAuthError if you can import the class.
if (err.name === "InteractionRequiredAuthError") {
return msalInstance.acquireTokenPopup(tokenRequest)
.then(response => {
// get access token from response
// response.accessToken
})
.catch(err => {
// handle error
});
}
});
} else {
// user is not logged in, you will need to log them in to acquire a token
}
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(resp => {
//do something with response
});
You can learn further details about MSAL.js functionality documented in the MSAL Wiki and find complete code samples.
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");
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.
FAQs
Microsoft Authentication Library for js
We found that msal demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.