1 |
|
2 | Microsoft Authentication Library for JavaScript (MSAL.js)
|
3 | =========================================================
|
4 |
|
5 | | [Getting Started](https://docs.microsoft.com/azure/active-directory/develop/guidedsetups/active-directory-javascriptspa)| [AAD Docs](https://aka.ms/aaddevv2) | [Library Reference](https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal.html) | [Support](README.md#community-help-and-support) | [Samples](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/Samples)
|
6 | | --- | --- | --- | --- | --- |
|
7 |
|
8 | ⚠️⚠️⚠️ 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](https://www.npmjs.com/package/@azure/msal-browser) instead. ⚠️⚠️⚠️
|
9 |
|
10 | MSAL for JavaScript enables client-side JavaScript web applications, running in a web browser, to authenticate users using [Azure AD](https://docs.microsoft.com/azure/active-directory/develop/v2-overview) work and school accounts (AAD), Microsoft personal accounts (MSA) and social identity providers like Facebook, Google, LinkedIn, Microsoft accounts, etc. through [Azure AD B2C](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-overview#identity-providers) service. It also enables your app to get tokens to access [Microsoft Cloud](https://www.microsoft.com/enterprise) services such as [Microsoft Graph](https://graph.microsoft.io).
|
11 |
|
12 | [![npm version](https://img.shields.io/npm/v/msal.svg?style=flat)](https://www.npmjs.com/package/msal)
|
13 | [![npm version](https://img.shields.io/npm/dm/msal.svg)](https://nodei.co/npm/msal/)
|
14 | [![codecov](https://codecov.io/gh/AzureAD/microsoft-authentication-library-for-js/branch/dev/graph/badge.svg?flag=msal-core)](https://codecov.io/gh/AzureAD/microsoft-authentication-library-for-js)
|
15 |
|
16 | ## Installation
|
17 |
|
18 | ### Via NPM:
|
19 |
|
20 | npm install msal
|
21 |
|
22 | ## Via CDN:
|
23 |
|
24 |
|
25 | ```html
|
26 | <script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.17/js/msal.min.js"></script>
|
27 | ```
|
28 |
|
29 | [Complete details and best practices](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-core/docs/cdn-usage.md) for CDN usage are available in our documentation.
|
30 |
|
31 | ## What To Expect From This Library
|
32 | 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`.
|
33 |
|
34 | 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.
|
35 |
|
36 | Please check our [roadmap](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki#roadmap) to see what we are working on and what we are tracking next.
|
37 |
|
38 | ## OAuth 2.0 and the Implicit Flow
|
39 |
|
40 | Msal implements the [Implicit Grant Flow](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-implicit-grant-flow), as defined by the OAuth 2.0 protocol and is [OpenID](https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc) compliant.
|
41 |
|
42 | 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.
|
43 | 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.
|
44 | 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.
|
45 |
|
46 | ## Cache Storage
|
47 |
|
48 | 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.
|
49 |
|
50 | ### forceRefresh to skip cache
|
51 | 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.
|
52 |
|
53 | ## Usage
|
54 | The example below walks you through how to login a user and acquire a token to be used for Microsoft's Graph Api.
|
55 |
|
56 | #### Prerequisites
|
57 |
|
58 | Before using MSAL.js you will need to [register an application in Azure AD](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app) to get a valid `clientId` for configuration, and to register the routes that your app will accept redirect traffic on.
|
59 |
|
60 | #### 1. Instantiate the UserAgentApplication
|
61 |
|
62 | `UserAgentApplication` can be configured with a variety of different options, detailed in our [Wiki](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL.js-1.0.0-api-release#configuration-options), but the only required parameter is `auth.clientId`.
|
63 |
|
64 | 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.
|
65 |
|
66 | ```JavaScript
|
67 | import * as Msal from "msal";
|
68 | // if using cdn version, 'Msal' will be available in the global scope
|
69 |
|
70 | const msalConfig = {
|
71 | auth: {
|
72 | clientId: 'your_client_id'
|
73 | }
|
74 | };
|
75 |
|
76 | const msalInstance = new Msal.UserAgentApplication(msalConfig);
|
77 |
|
78 | msalInstance.handleRedirectCallback((error, response) => {
|
79 | // handle redirect response or error
|
80 | });
|
81 |
|
82 | ```
|
83 |
|
84 | For details on the configuration options, read [Initializing client applications with MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-initializing-client-applications).
|
85 |
|
86 | #### 2. Login the user
|
87 |
|
88 | Your app must login the user with either the `loginPopup` or the `loginRedirect` method to establish user context.
|
89 |
|
90 | When the login methods are called and the authentication of the user is completed by the Azure AD service, an [id token](https://docs.microsoft.com/azure/active-directory/develop/id-tokens) is returned which is used to identify the user with some basic information.
|
91 |
|
92 | 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.
|
93 |
|
94 | 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.
|
95 |
|
96 | AAD will only allow you to get consent for 3 resources at a time, although you can request many scopes within a resource.
|
97 | 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.
|
98 |
|
99 | ```JavaScript
|
100 | var loginRequest = {
|
101 | scopes: ["user.read", "mail.send"] // optional Array<string>
|
102 | };
|
103 |
|
104 | msalInstance.loginPopup(loginRequest)
|
105 | .then(response => {
|
106 | // handle response
|
107 | })
|
108 | .catch(err => {
|
109 | // handle error
|
110 | });
|
111 |
|
112 | ```
|
113 |
|
114 | ##### ssoSilent
|
115 |
|
116 | 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](https://docs.microsoft.com/azure/active-directory/develop/active-directory-optional-claims)) and MSAL will attempt to silently SSO to the existing session and establish user context.
|
117 |
|
118 | 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`).
|
119 |
|
120 | Example:
|
121 |
|
122 | ```js
|
123 | const ssoRequest = {
|
124 | loginHint: "user@example.com"
|
125 | };
|
126 |
|
127 | msalInstance.ssoSilent(ssoRequest)
|
128 | .then(response => {
|
129 | // session silently established
|
130 | })
|
131 | .catch(error => {
|
132 | // handle error by invoking an interactive login method
|
133 | msalInstance.loginPopup(ssoRequest);
|
134 | });
|
135 | ```
|
136 |
|
137 | #### 3. Get an access token to call an API
|
138 |
|
139 | 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](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) containing the user consented scopes to allow your app to securely call the API.
|
140 |
|
141 | 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`).
|
142 |
|
143 | 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.
|
144 |
|
145 | `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.
|
146 |
|
147 | See [Request and Response Data Types](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL.js-1.0.0-api-release#signing-in-and-getting-tokens-with-msaljs) for reference.
|
148 |
|
149 | ```JavaScript
|
150 | // if the user is already logged in you can acquire a token
|
151 | if (msalInstance.getAccount()) {
|
152 | var tokenRequest = {
|
153 | scopes: ["user.read", "mail.send"]
|
154 | };
|
155 | msalInstance.acquireTokenSilent(tokenRequest)
|
156 | .then(response => {
|
157 | // get access token from response
|
158 | // response.accessToken
|
159 | })
|
160 | .catch(err => {
|
161 | // could also check if err instance of InteractionRequiredAuthError if you can import the class.
|
162 | if (err.name === "InteractionRequiredAuthError") {
|
163 | return msalInstance.acquireTokenPopup(tokenRequest)
|
164 | .then(response => {
|
165 | // get access token from response
|
166 | // response.accessToken
|
167 | })
|
168 | .catch(err => {
|
169 | // handle error
|
170 | });
|
171 | }
|
172 | });
|
173 | } else {
|
174 | // user is not logged in, you will need to log them in to acquire a token
|
175 | }
|
176 | ```
|
177 |
|
178 | #### 4. Use the token as a bearer in an HTTP request to call the Microsoft Graph or a Web API
|
179 |
|
180 | ```JavaScript
|
181 | var headers = new Headers();
|
182 | var bearer = "Bearer " + token;
|
183 | headers.append("Authorization", bearer);
|
184 | var options = {
|
185 | method: "GET",
|
186 | headers: headers
|
187 | };
|
188 | var graphEndpoint = "https://graph.microsoft.com/v1.0/me";
|
189 |
|
190 | fetch(graphEndpoint, options)
|
191 | .then(resp => {
|
192 | //do something with response
|
193 | });
|
194 | ```
|
195 |
|
196 | You can learn further details about MSAL.js functionality documented in the [MSAL Wiki](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki) and find complete [code samples](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/Samples).
|
197 |
|
198 | ## Security Reporting
|
199 |
|
200 | If you find a security issue with our libraries or services please report it to [secure@microsoft.com](mailto:secure@microsoft.com) with as much detail as possible. Your submission may be eligible for a bounty through the [Microsoft Bounty](http://aka.ms/bugbounty) 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](https://technet.microsoft.com/security/dd252948) and subscribing to Security Advisory Alerts.
|
201 |
|
202 | ## License
|
203 |
|
204 | Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");
|
205 |
|
206 | ## We Value and Adhere to the Microsoft Open Source Code of Conduct
|
207 |
|
208 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
|