@azure/msal-browser
Advanced tools
Comparing version 2.0.0-alpha.0 to 2.0.0-beta.0
@@ -0,2 +1,33 @@ | ||
# 2.0.0-beta.0 | ||
## Features | ||
* Removed client_secret from config and added docs for new registration experience (#1421) | ||
## Enhancements | ||
* Test pipelines in place. (#1393) | ||
* Added docs and samples. (#1421, #1321) | ||
## Bugs | ||
* Minor bug fixes from unit testing. (#1236) | ||
* navigateToLoginRequestUrl works correctly (#1320) | ||
# 2.0.0-alpha.0 | ||
## Features | ||
* Added Rollup as build tool (#1108) | ||
* Added APIs and major type files (#1109) | ||
* Added tests and code coverage (#1127) | ||
* Added Authority and protocol classes (#1133) | ||
* Added browser storage implementation (#1140) | ||
* Added implementation of crypto for browser (#1141) | ||
* Added fetch client (#1144) | ||
* Creating of login url (#1149) | ||
* Added logger class (#1155) | ||
* Added redirect handling code (#1164) | ||
* Successful token exchange (#1181) | ||
* Response handling code (#1183) | ||
* Token caching (#1185) | ||
* Popup handling (#1190) | ||
* Silent renewal using refresh tokens and logout (#1208) | ||
* SSO fixes for login_hint (#1211) | ||
# 0.0.1 | ||
- Created library with initial files for repo structure, build and package dependencies | ||
- Created library with initial files for repo structure, build and package dependencies |
@@ -38,3 +38,7 @@ import { Account, AuthenticationParameters, TokenResponse, TokenRenewParameters } from "@azure/msal-common"; | ||
/** | ||
* Set the callback functions for the redirect flow to send back the success or error object. | ||
* Set the callback functions for the redirect flow to send back the success or error object, and process | ||
* any redirect-related data. | ||
* IMPORTANT: Please do not use this function when using the popup APIs, as it may break the response handling | ||
* in the main window. | ||
* | ||
* @param {@link (AuthCallback:type)} authCallback - Callback which contains | ||
@@ -47,2 +51,14 @@ * an AuthError object, containing error data from either the server | ||
/** | ||
* Checks if navigateToLoginRequestUrl is set, and: | ||
* - if true, performs logic to cache and navigate | ||
* - if false, handles hash string and parses response | ||
*/ | ||
private handleRedirectResponse; | ||
/** | ||
* Checks if hash exists and handles in window. Otherwise, cancel any current requests and continue. | ||
* @param responseHash | ||
* @param interactionHandler | ||
*/ | ||
private handleHash; | ||
/** | ||
* Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so | ||
@@ -122,3 +138,10 @@ * any code that follows this function will not execute. | ||
getAccount(): Account; | ||
/** | ||
* Helper to check whether interaction is in progress | ||
*/ | ||
private interactionInProgress; | ||
/** | ||
* Helper to remove interaction status and remove tempoarary request data. | ||
*/ | ||
private cleanRequest; | ||
} |
@@ -29,2 +29,14 @@ /** | ||
private hasCryptoAPI; | ||
/** | ||
* Helper function for SHA digest. | ||
* @param algorithm | ||
* @param data | ||
*/ | ||
private getSubtleCryptoDigest; | ||
/** | ||
* Helper function for SHA digest. | ||
* @param algorithm | ||
* @param data | ||
*/ | ||
private getMSCryptoDigest; | ||
} |
@@ -6,2 +6,7 @@ import { BrowserCrypto } from "./BrowserCrypto"; | ||
generateGuid(): string; | ||
/** | ||
* verifies if a string is GUID | ||
* @param guid | ||
*/ | ||
static isGuid(guid: string): boolean; | ||
} |
@@ -38,2 +38,6 @@ import { AuthError } from "@azure/msal-common"; | ||
}; | ||
emptyWindowError: { | ||
code: string; | ||
desc: string; | ||
}; | ||
userCancelledError: { | ||
@@ -47,2 +51,6 @@ code: string; | ||
}; | ||
redirectInIframeError: { | ||
code: string; | ||
desc: string; | ||
}; | ||
}; | ||
@@ -92,2 +100,7 @@ /** | ||
/** | ||
* Creates an error thrown when window.open returns an empty window object. | ||
* @param errDetail | ||
*/ | ||
static createEmptyWindowCreatedError(): BrowserAuthError; | ||
/** | ||
* Creates an error thrown when the user closes a popup. | ||
@@ -97,6 +110,11 @@ */ | ||
/** | ||
* Creates an error thrown when the | ||
* Creates an error thrown when monitorWindowFromHash times out for a given popup. | ||
* @param urlNavigate | ||
*/ | ||
static createPopupWindowTimeoutError(urlNavigate: string): BrowserAuthError; | ||
/** | ||
* Creates an error thrown when navigateWindow is called inside an iframe. | ||
* @param windowParentCheck | ||
*/ | ||
static createRedirectInIframeError(windowParentCheck: boolean): BrowserAuthError; | ||
} |
@@ -1,3 +0,4 @@ | ||
import { TokenResponse } from "@azure/msal-common"; | ||
import { TokenResponse, AuthorizationCodeModule } from "@azure/msal-common"; | ||
import { InteractionHandler } from "./InteractionHandler"; | ||
import { BrowserStorage } from "../cache/BrowserStorage"; | ||
/** | ||
@@ -9,2 +10,3 @@ * This class implements the interaction handler base class for browsers. It is written specifically for handling | ||
private currentWindow; | ||
constructor(authCodeModule: AuthorizationCodeModule, storageImpl: BrowserStorage); | ||
/** | ||
@@ -40,2 +42,11 @@ * Opens a popup window with given request Url. | ||
private openPopup; | ||
/** | ||
* Event callback to unload main window. | ||
*/ | ||
unloadWindow(e: Event): void; | ||
/** | ||
* Closes popup, removes any state vars created during popup calls. | ||
* @param popupWindow | ||
*/ | ||
private cleanPopup; | ||
} |
@@ -1,7 +0,4 @@ | ||
import { AuthorizationCodeModule, TokenResponse } from "@azure/msal-common"; | ||
import { TokenResponse } from "@azure/msal-common"; | ||
import { InteractionHandler } from "./InteractionHandler"; | ||
import { BrowserStorage } from "../cache/BrowserStorage"; | ||
export declare class RedirectHandler extends InteractionHandler { | ||
private navigateToLoginRequestUrl; | ||
constructor(authCodeModule: AuthorizationCodeModule, storageImpl: BrowserStorage, navigateToLoginRequestUrl: boolean); | ||
/** | ||
@@ -8,0 +5,0 @@ * Redirects window to given URL. |
@@ -9,5 +9,14 @@ import { INetworkModule } from "@azure/msal-common"; | ||
* @param {string} urlNavigate - URL of the authorization endpoint | ||
* @param {boolean} noHistory - boolean flag, uses .replace() instead of .assign() if true | ||
*/ | ||
static navigateWindow(urlNavigate: string): void; | ||
static navigateWindow(urlNavigate: string, noHistory?: boolean): void; | ||
/** | ||
* Clears hash from window url. | ||
*/ | ||
static clearHash(): void; | ||
/** | ||
* Returns boolean of whether the current window is in an iframe or not. | ||
*/ | ||
static isInIframe(): boolean; | ||
/** | ||
* Returns current window URL as redirect uri | ||
@@ -14,0 +23,0 @@ */ |
@@ -13,3 +13,3 @@ { | ||
}, | ||
"version": "2.0.0-alpha.0", | ||
"version": "2.0.0-beta.0", | ||
"description": "Microsoft Authentication Library for js", | ||
@@ -41,2 +41,5 @@ "keywords": [ | ||
"lint": "eslint src --ext .ts", | ||
"doc": "npm run doc:generate && npm run doc:deploy", | ||
"doc:generate": "typedoc --mode modules --excludePrivate --excludeProtected --out ./ref ./src/ --gitRevision dev", | ||
"doc:deploy": "gh-pages -d ref -a -e ref/msal-browser", | ||
"pretest": "npm link @azure/msal-common", | ||
@@ -51,3 +54,3 @@ "test": "mocha", | ||
"build": "npm run clean && npm run lint && npm run build:modules", | ||
"prepack": "npm run build" | ||
"prepack": "npm run build:all" | ||
}, | ||
@@ -75,2 +78,3 @@ "devDependencies": { | ||
"eslint": "^6.5.1", | ||
"gh-pages": "^2.2.0", | ||
"husky": "^3.0.9", | ||
@@ -80,3 +84,3 @@ "jsdom": "^15.2.1", | ||
"mocha": "^6.2.2", | ||
"nyc": "^14.1.1", | ||
"nyc": "^15.0.0", | ||
"rimraf": "^3.0.0", | ||
@@ -86,3 +90,3 @@ "rollup": "^1.24.0", | ||
"rollup-plugin-typescript2": "^0.24.3", | ||
"rollup-plugin-uglify": "^6.0.3", | ||
"rollup-plugin-uglify": "^6.0.4", | ||
"shx": "^0.3.2", | ||
@@ -92,7 +96,8 @@ "sinon": "^7.5.0", | ||
"tslint": "^5.20.0", | ||
"typedoc": "^0.16.11", | ||
"typescript": "^3.6.4" | ||
}, | ||
"dependencies": { | ||
"@azure/msal-common": "1.0.0-alpha.0" | ||
"@azure/msal-common": "1.0.0-beta.0" | ||
} | ||
} |
263
README.md
@@ -1,212 +0,153 @@ | ||
Microsoft Authentication Library for JavaScript (MSAL.js) (DRAFT) | ||
========================================================= | ||
# (Preview) Microsoft Authentication Library for JavaScript (MSAL.js) 2.0 for Browser-Based Single-Page Applications | ||
[![npm version](https://img.shields.io/npm/v/@azure/msal-browser.svg?style=flat)](https://www.npmjs.com/package/@azure/msal-browser/)[![npm version](https://img.shields.io/npm/dm/@azure/msal-browser.svg)](https://nodei.co/npm/@azure/msal-browser/)[![Coverage Status](https://coveralls.io/repos/github/AzureAD/microsoft-authentication-library-for-js/badge.svg?branch=dev)](https://coveralls.io/github/AzureAD/microsoft-authentication-library-for-js?branch=dev) | ||
| [Getting Started](https://docs.microsoft.com/en-us/azure/active-directory/develop/guidedsetups/active-directory-javascriptspa)| [AAD Docs](https://aka.ms/aaddevv2) | [Library Reference](https://htmlpreview.github.io/?https://raw.githubusercontent.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-core/docs/classes/_useragentapplication_.useragentapplication.html) | [Support](README.md#community-help-and-support) | [Samples](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/Samples) | ||
| --- | --- | --- | --- | --- | | ||
| <a href="https://docs.microsoft.com/azure/active-directory/develop/guidedsetups/active-directory-javascriptspa" target="_blank">Getting Started</a> | <a href="https://aka.ms/aaddevv2" target="_blank">AAD Docs</a> | <a href="https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-browser/" target="_blank">Library Reference</a> | | ||
| --- | --- | --- | | ||
1. [About](#about) | ||
2. [FAQ](./FAQ.md) | ||
3. [Releases](#releases) | ||
4. [Prerequisites](#prerequisites) | ||
5. [Installation](#installation) | ||
6. [Usage](#usage) | ||
- [Migrating from Previous MSAL Versions](#migrating-from-previous-msal-versions) | ||
- [MSAL Basics](#msal-basics) | ||
- [Advanced Topics](#advanced-topics) | ||
7. [Samples](#samples) | ||
8. [Build and Test](#build-and-test) | ||
8. [Authorization Code vs Implicit](#oauth-2.0-and-the-implicit-flow-vs-authorization-code-flow-with-pkce) | ||
9. [Security Reporting](#security-reporting) | ||
10. [License](#license) | ||
11. [Code of Conduct](#we-value-and-adhere-to-the-microsoft-open-source-code-of-conduct) | ||
The MSAL library for JavaScript enables client-side JavaScript applications to authenticate users using [Azure AD](https://docs.microsoft.com/en-us/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/en-us/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). | ||
## About | ||
[![Build Status](https://travis-ci.org/AzureAD/microsoft-authentication-library-for-js.png?branch=dev)](https://travis-ci.org/AzureAD/microsoft-authentication-library-for-js)[![npm version](https://img.shields.io/npm/v/msal.svg?style=flat)](https://www.npmjs.com/package/msal)[![npm version](https://img.shields.io/npm/dm/msal.svg)](https://nodei.co/npm/msal/) | ||
The MSAL library for JavaScript enables client-side JavaScript applications 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). | ||
## Installation | ||
### Via NPM (Not available yet): | ||
The `@azure/msal-browser` package described by the code in this folder uses the [`@azure/msal-common` package](../msal-common/) as a dependency to enable authentication in Javascript Single-Page Applications without backend servers. This version of the library uses the OAuth 2.0 Authorization Code Flow with PKCE. To read more about this protocol, as well as the differences between implicit flow and authorization code flow, see the section [below](#oauth-2.0-and-the-implicit-flow-vs-authorization-code-flow-with-pkce). If you are looking for the version of the library that uses the implicit flow, please see the [`msal-core` library](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core). | ||
npm install @azure/msal-browser | ||
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. The `@azure/msal-browser` package does NOT support the implicit flow. | ||
## Build and Run | ||
**IMPORTANT:** Please be aware that this is not a production ready library. We are making changes in the [Azure portal](https://azure.microsoft.com/en-us/features/azure-portal/) to ensure we can deliver a polished end-to-end experience. | ||
### Build Library | ||
```javascript | ||
// 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 | ||
``` | ||
## FAQ | ||
### Run | ||
To run sample, ensure the client_id and client_secret are updated and filled in. | ||
See [here](./FAQ.md). | ||
```Javascript | ||
cd samples/VanillaJSTestApp | ||
npm start | ||
``` | ||
## Releases | ||
## About this library - Authorization Code Flow (Alpha) | ||
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. | ||
*Expect us to detail our major and minor releases moving forward, while leaving out our patch releases. Patch release notes can be found in our change log.* | ||
**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. | ||
| Date | Release | Announcement | Main features | | ||
| ------| ------- | ---------| --------- | | ||
| | @azure/msal-browser v2.0.0-beta | No release notes yet | Beta version of the `@azure/msal-browser` package; relies on `@azure/msal-common` v1.0.0-beta | | ||
| January 17, 2020 | @azure/msal-browser v2.0.0-alpha | No release notes yet | Alpha version of the `@azure/msal-browser` package with authorization code flow for SPAs working in dev; relies on msal-common v1.0.0-alpha | | ||
## Samples | ||
## Prerequisites | ||
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. | ||
- `@azure/msal-browser` is meant to be used in [Single-Page Application scenarios](https://docs.microsoft.com/azure/active-directory/develop/scenario-spa-overview). | ||
### Pre-requisites | ||
- Before using `@azure/msal-browser` 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. | ||
1. Create a new application registration in the portal. Use whatever audience you wish, as long as it is testable on your machine. It is recommended to use the common audience (a.k.a. accounts in any Azure tenant) for simplest use. | ||
- Go to the Authentication tab. Register the redirect URI for the application as "http://localhost:30662/". Also select "Yes" when asked if you would like to treat this application as a public client. | ||
- Go the Certificates & Secrets tab. Create a Client Secret that you can use for testing. This will most likely not be a required step in future production versions for Auth Code in the browser, but for now in order to run the alpha you will need to create one. | ||
2. Keep the app registration page open. You will now need a browser with CORS disabled in order to be able to retrieve tokens from the token endpoint. This is once again not a recommended production setting, but for the purposes of this alpha you should follow these instructions: | ||
- We recommend using Chrome for this. | ||
- For Windows machines, you can do the following: | ||
- Right click on your desktop -> New -> Shortcut | ||
- Paste the following: | ||
```javascript | ||
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp | ||
``` | ||
- Click next and create a name for the shortcut (i.e. Chrome-no-cors) | ||
- For other machines, you can follow the steps [here](https://alfilatov.com/posts/run-chrome-without-cors/) to figure out how to run Chrome withput CORS enabled for your OS. | ||
3. You should now have a shortcut for a CORS-disabled Chrome browser and an application registration for a public client with the correct redirect URI registered and a client secret. You can now run the sample! When you run the browser shortcut, ensure you run as an administrator. | ||
- Once you have registered your application, you will need to do two things in order to ensure `@azure/msal-browser` will successfully retrieve tokens: | ||
1. Change your redirect URI type to enable CORS. You can do this by going to the manifest editor for your app registration in the portal, finding the `replyUrlsWithType` section and changing the type of your redirect URI to `SPA`. This may remove the affected redirect URIs from the Web platform Authentication tab - that's OK! We are working on getting UI set up for this. | ||
## Roadmap and What To Expect From This Library | ||
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. | ||
![Changing Redirect URI type](./docs/images/redirectURIRegistrationUpdate.png) | ||
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. | ||
2. Ensure your `Default Client Type` settings have "Treat application as public client" set to "Yes". | ||
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. | ||
![Changing Default Client type](./docs/images/clientTypeRegistrationUpdate.png) | ||
## OAuth 2.0 and the Implicit Flow vs Authorization Code Flow with PKCE | ||
MSAL formerly only implemented the [Implicit Grant Flow](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow), as defined by the OAuth 2.0 protocol and [OpenID](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc). | ||
## Installation | ||
### Via NPM: | ||
```javascript | ||
npm install @azure/msal-browser | ||
``` | ||
### Via CDN: | ||
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. | ||
## Usage | ||
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](https://tools.ietf.org/html/draft-ietf-oauth-browser-based-apps-04#section-9.8.6). | ||
### Migrating from Previous MSAL Versions | ||
We plan to continue support for the implicit flow in the library. | ||
If you have MSAL v1.x currently running in your application, you can follow the instructions [here](./docs/v1-migration.md) to migrate your application to using the `@azure/msal-browser` package. | ||
## Usage | ||
The example below walks you through how to login a user and acquire a token to be used for Microsoft's Graph Api. | ||
### MSAL Basics | ||
#### Prerequisites | ||
1. [Initialization](./docs/initialization.md) | ||
2. [Logging in a User](./docs/login-user.md) | ||
3. [Acquiring and Using an Access Token](./docs/acquire-token.md) | ||
4. [Managing Token Lifetimes](./docs/token-lifetimes.md) | ||
5. [Logging Out a User](./docs/logout.md) | ||
Before using MSAL.js you will need to [register an application in Azure AD](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app) to get a valid `clientId` and `clientSecret` for configuration, and to register the routes that your app will accept redirect traffic on. | ||
### Advanced Topics | ||
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. | ||
- [Configuration Options](./docs/configuration.md) | ||
- [Request and Response Details](./docs/request-response-object.md) | ||
- [Cache Storage](./docs/caching.md) | ||
#### 1. Initializing the Public Client Application | ||
## Samples | ||
`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. | ||
The [`VanillaJSTestApp2.0` folder](../../samples/VanillaJSTestApp2.0) contains sample applications for our libraries. You can run any sample by changing the `authConfig.js` file in the respective folder to match your app registration and running the `npm` command `npm start -- -s <sample-name> -p <port>`. | ||
```javascript | ||
import * as msal from "@azure/msal-browser"; | ||
Here is a complete list of samples for the MSAL.js 2.x library: | ||
const msalConfig = { | ||
auth: { | ||
clientId: 'your_client_id', | ||
tmp_clientSecret: 'tmp_secret1' | ||
} | ||
}; | ||
| Sample | Description | How to Run | | ||
| ------ | ----------- | ---------- | | ||
| [Basic Auth Sample](../../samples/VanillaJSTestApp2.0/default) | A vanilla Javascript sample showing basic usage of the MSAL 2.0 library (`@azure/msal-browser` package) with the Microsoft Graph API. | `npm start -- -s default` | | ||
const msalInstance = new msal.PublicClientApplication(msalConfig); | ||
``` | ||
More instructions to run the sample can be found in the [`README.md` file](../../samples/VanillaJSTestApp2.0/README.md) of the VanillaJSTestApp2.0 folder. | ||
#### 2. Choose interaction type - redirect or popup | ||
## Build and Test | ||
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. | ||
### Build Library | ||
```javascript | ||
msalInstance.handleRedirectCallback((error, response) => { | ||
// handle redirect response or error | ||
}); | ||
// Change to the root of the msal repo | ||
cd microsoft-authentication-library-for-js/ | ||
// Install npm dependencies and bootstrap packages | ||
npm install | ||
// Build library | ||
npm run build | ||
// To run build only for the browser package | ||
npm run build -- --scope @azure/msal-browser | ||
``` | ||
#### 3. Login the user | ||
#### Alternate Build Instructions | ||
If you are having issues with `lerna`, you can try the following: | ||
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](https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens) 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. | ||
```JavaScript | ||
var loginRequest = { | ||
scopes: ["user.read", "mail.send"] // optional Array<string> | ||
}; | ||
msalInstance.loginPopup(loginRequest) | ||
.then(response => { | ||
// handle response | ||
}) | ||
.catch(err => { | ||
// handle error | ||
}); | ||
```javascript | ||
// Change to the msal-browser package directory | ||
cd lib/msal-browser/ | ||
// Ensure you are using the local build of msal-common | ||
npm link @azure/msal-common | ||
// To run build only for browser package | ||
npm run build | ||
// To run build for common and browser package | ||
npm run build:all | ||
``` | ||
#### 4. Get an access token to call an API | ||
### Running Tests | ||
`@azure/msal-browser` uses [mocha](https://mochajs.org/) and [chai](https://www.chaijs.com/) to run unit tests, as well as Istanbul's [nyc](https://github.com/istanbuljs/nyc) tool for code coverage. | ||
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/en-us/azure/active-directory/develop/access-tokens) 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. | ||
```JavaScript | ||
// 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 | ||
} | ||
```javascript | ||
// To run tests | ||
npm test | ||
// To run tests with code coverage | ||
npm run test:coverage:only | ||
``` | ||
#### 5. Use the token as a bearer in an HTTP request to call the Microsoft Graph or a Web API | ||
- If you are having issues with `lerna`, change to the `msal-browser` directory and run the commands directly there. | ||
```JavaScript | ||
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"; | ||
## OAuth 2.0 and the Implicit Flow vs Authorization Code Flow with PKCE | ||
MSAL.js 1.x implemented 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 [OpenID](https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc). | ||
fetch(graphEndpoint, options) | ||
.then(resp => { | ||
//do something with response | ||
}); | ||
``` | ||
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 MSAL 1.x client for single-page applications runs in the context of a web browser which cannot manage client secrets securely. It uses the implicit flow, which 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. You can read more about the [disadvantages of the implicit flow here](https://tools.ietf.org/html/draft-ietf-oauth-browser-based-apps-04#section-9.8.6). | ||
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). | ||
The MSAL library will now support the Authorization Code Flow with PKCE for Browser-Based Applications without a backend web server. | ||
We plan to continue support for the implicit flow in the `msal-core` library. | ||
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). | ||
You can learn further details about `@azure/msal-browser` functionality documented in our [docs folder](./docs) and find complete [code samples](#samples). | ||
## Cache Storage | ||
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. | ||
### forceRefresh to skip cache | ||
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. | ||
## Security Reporting | ||
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/en-us/security/dd252948) and subscribing to Security Advisory Alerts. | ||
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. | ||
@@ -213,0 +154,0 @@ ## License |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1814985
11106
37
161
+ Added@azure/msal-common@1.0.0-beta.0(transitive)
- Removed@azure/msal-common@1.0.0-alpha.0(transitive)