Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
@azure/msal-browser
Advanced tools
The @azure/msal-browser package is a library that enables browser-based applications to authenticate users using Azure Active Directory and to obtain tokens to access protected APIs. It implements the OAuth 2.0 and OpenID Connect protocols in a client-side JavaScript application.
Authentication
This feature allows users to sign in and obtain an ID token through a popup window.
const msalConfig = {
auth: {
clientId: 'your-client-id',
authority: 'https://login.microsoftonline.com/common',
redirectUri: 'your-redirect-uri'
}
};
const myMSALObj = new msal.PublicClientApplication(msalConfig);
function signIn() {
myMSALObj.loginPopup()
.then(loginResponse => {
console.log('id_token acquired at: ' + new Date().toString());
if (myMSALObj.getAccount()) {
console.log('Logged in');
}
}).catch(error => {
console.error(error);
});
}
Acquiring Tokens
This feature is used to acquire tokens silently or through a popup if required by the application.
const tokenRequest = {
scopes: ['user.read'],
forceRefresh: false
};
function getTokenPopup(request) {
return myMSALObj.acquireTokenSilent(request)
.catch(error => {
console.warn('silent token acquisition fails. acquiring token using popup');
if (error instanceof msal.InteractionRequiredAuthError) {
return myMSALObj.acquireTokenPopup(request)
.then(tokenResponse => {
return tokenResponse;
}).catch(error => {
console.error(error);
});
} else {
console.warn(error);
}
});
}
Single Sign-Out
This feature allows users to sign out of the application and clear the user's session.
function signOut() {
const logoutRequest = {
account: myMSALObj.getAccount()
};
myMSALObj.logout(logoutRequest);
}
The oidc-client package is a low-level JavaScript library for implementing OpenID Connect (OIDC) clients in the browser. It provides more granular control over the authentication process compared to @azure/msal-browser but requires more setup and understanding of the OIDC protocol.
The react-adal package is a React library that provides Azure Active Directory Authentication in ReactJS applications. It is specifically tailored for React applications and uses the ADAL.js library under the hood. It is less modern and feature-rich compared to @azure/msal-browser, which uses the newer MSAL.js library.
The angular-auth-oidc-client package is an Angular library for implementing OpenID Connect and OAuth2 in Angular applications. It is designed specifically for Angular and provides a similar feature set to @azure/msal-browser but is tailored to the Angular framework.
Getting Started | AAD Docs | Library Reference | Support | Samples |
---|
The MSAL library for JavaScript enables client-side JavaScript applications 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 @azure/msal-browser
// bootstrap for sym-links (go to base folder)
lerna bootstrap
cd /lib/msal-common/
// To run build only for browser package
npm run build
// To run build for common and browser package
npm run build:all
To run sample, ensure the client_id and client_secret are updated and filled in.
cd samples/VanillaJSTestApp
npm start
This is an improvement upon the current msal-core
library which will utilize the authorization code flow in the browser. Most features available in the old library will be available in this one, but there are nuances to the authentication flow in both.
IMPORTANT: Please be aware that this is not a production ready library. You are required to use a browser that disables CORS checks, and will be exposing a client secret. The server will be making changes that will allow CORS requests and remove the requirement for client secret for applications which are registered in a specific way, and we will have documentation explaining this when the features are available.
The current VanillaJSTestApp sample is set up to run the authorization code flow in the browser. However, there are a few pre-requisites that you will need to complete before being able to run the VanillaJS sample.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
MSAL support on Javascript is a collection of libraries. msal-common
is the platform agnostic core library, and msal-browser
is our core library for Single Page Applications (SPAs) without a backend. This library includes improvements for new browser requirements in Safari, as well as an updated token acquisition flow utilizing the OAuth 2.0 Authorization Code Flow.
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 comming 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 formerly only implemented the Implicit Grant Flow, as defined by the OAuth 2.0 protocol and OpenID.
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.
However, recent discussion among the IETF community has uncovered numerous vulnerabilities in the implicit flow. The MSAL library will now support the Authorization Code Flow with PKCE for Browser-Based Applications without a backend web server. You can read more about the disadvantages of the implicit flow here.
We plan to continue support for the implicit flow in the library.
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
and clientSecret
for configuration, and to register the routes that your app will accept redirect traffic on.
Once you have created an application registration, create a new secret in the Certificates & Secrets
section. IMPORTANT NOTE: Client secret will not be carried forward in production versions of the library. This is temporary until the server allows CORS requests from public clients.
PublicClientApplication
can be configured with a variety of different options, detailed in our Wiki, but the only required parameters are auth.clientId
and auth.tmp_clientSecret
. IMPORTANT NOTE: Client secret will not be carried forward in production versions of the library. This is temporary until the server allows CORS requests from public clients.
import * as msal from "@azure/msal-browser";
const msalConfig = {
auth: {
clientId: 'your_client_id',
tmp_clientSecret: 'tmp_secret1'
}
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
Choose which APIs you will use in your authentication flows:
loginRedirect
and acquireTokenRedirect
loginPopup
and acquireTokenPopup
If you are using the redirect APIs, you will need to include the helper function below with a valid callback API. If you do not use this, your application will error out if any of the redirect APIs are used. This is not needed for any popup APIs.
msalInstance.handleRedirectCallback((error, response) => {
// handle redirect response or error
});
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
});
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, you may 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 => {
// 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.
You can learn further details about MSAL.js functionality documented in the MSAL Wiki and find complete code samples.
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 encourage 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.
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
The npm package @azure/msal-browser receives a total of 2,522,209 weekly downloads. As such, @azure/msal-browser popularity was classified as popular.
We found that @azure/msal-browser demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers 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
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.