From e1b1a9403aa0331a27f67717eb5e12fab61c3372 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 17 Mar 2023 12:34:21 +0300 Subject: [PATCH 01/20] test cross -repo reference for msal.js --- .openpublishing.publish.config.json | 6 ++++++ msal/docs-ref-toc/fxtoc.yml | 2 +- msal/overview/msal-react.md | 20 ++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 msal/overview/msal-react.md diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index d27d2bd..27ba746 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -49,6 +49,12 @@ "url": "https://github.com/Microsoft/templates.docs.msft", "branch": "main", "branch_mapping": {} + }, + { + "path_to_root": "/lib", + "url": "https://github.com/AzureAD/microsoft-authentication-library-for-js", + "branch": "dev", + "branch_mapping": {} } ], "branch_target_mapping": {}, diff --git a/msal/docs-ref-toc/fxtoc.yml b/msal/docs-ref-toc/fxtoc.yml index 4b0c332..51377cf 100644 --- a/msal/docs-ref-toc/fxtoc.yml +++ b/msal/docs-ref-toc/fxtoc.yml @@ -2,6 +2,6 @@ uid: msal.sdk.landingPage.reference landingPageType: Root expanded: true - href: ~/overview/msal-overview.md + href: ~/overview/msal-react.md children: - '**' \ No newline at end of file diff --git a/msal/overview/msal-react.md b/msal/overview/msal-react.md new file mode 100644 index 0000000..0f07c32 --- /dev/null +++ b/msal/overview/msal-react.md @@ -0,0 +1,20 @@ +--- +title: MSAL React +description: Overview of the Microsoft Authentication Libraries for JavaScript +services: active-directory +author: Dickson-Mwendia +manager: CelesteDG + +ms.service: active-directory +ms.subservice: develop +ms.topic: reference +ms.workload: identity +ms.date: 01/10/2023 +ms.author: dmwendia +--- + + +# Getting started with MSAL React + + +[!INCLUDE[MSAL React getting started](~/lib/msal-react/docs/getting-started.md)] \ No newline at end of file From 32fdf6b74b9f3f3472ae65074127ef3e005b7fc5 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 17 Mar 2023 12:45:46 +0300 Subject: [PATCH 02/20] update root --- .openpublishing.publish.config.json | 2 +- msal/overview/msal-react.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 27ba746..c7c752f 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -51,7 +51,7 @@ "branch_mapping": {} }, { - "path_to_root": "/lib", + "path_to_root": "microsoft-authentication-library-for-js", "url": "https://github.com/AzureAD/microsoft-authentication-library-for-js", "branch": "dev", "branch_mapping": {} diff --git a/msal/overview/msal-react.md b/msal/overview/msal-react.md index 0f07c32..17265b5 100644 --- a/msal/overview/msal-react.md +++ b/msal/overview/msal-react.md @@ -1,6 +1,6 @@ --- title: MSAL React -description: Overview of the Microsoft Authentication Libraries for JavaScript +description: Getting started with MSAL React services: active-directory author: Dickson-Mwendia manager: CelesteDG From 9150de0085fe7817bf0f753c0372a53772a050d1 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 17 Mar 2023 12:48:14 +0300 Subject: [PATCH 03/20] update path to dependent repo --- msal/overview/msal-react.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/msal/overview/msal-react.md b/msal/overview/msal-react.md index 17265b5..74a86b2 100644 --- a/msal/overview/msal-react.md +++ b/msal/overview/msal-react.md @@ -17,4 +17,4 @@ ms.author: dmwendia # Getting started with MSAL React -[!INCLUDE[MSAL React getting started](~/lib/msal-react/docs/getting-started.md)] \ No newline at end of file +[!INCLUDE[MSAL React getting started](~/microsoft-authentication-library-javascript/lib/msal-react/docs/getting-started.md)] \ No newline at end of file From 29868997e116f48028880e1f3caba03d2ec8679a Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 17 Mar 2023 13:09:40 +0300 Subject: [PATCH 04/20] try fixing include bug --- .openpublishing.publish.config.json | 2 +- msal/overview/msal-react.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index c7c752f..1c67334 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -51,7 +51,7 @@ "branch_mapping": {} }, { - "path_to_root": "microsoft-authentication-library-for-js", + "path_to_root": "lib", "url": "https://github.com/AzureAD/microsoft-authentication-library-for-js", "branch": "dev", "branch_mapping": {} diff --git a/msal/overview/msal-react.md b/msal/overview/msal-react.md index 74a86b2..6845510 100644 --- a/msal/overview/msal-react.md +++ b/msal/overview/msal-react.md @@ -17,4 +17,4 @@ ms.author: dmwendia # Getting started with MSAL React -[!INCLUDE[MSAL React getting started](~/microsoft-authentication-library-javascript/lib/msal-react/docs/getting-started.md)] \ No newline at end of file +[!INCLUDE[MSAL React getting started](~/msal-react/docs/getting-started.md)] \ No newline at end of file From 874174f46d294e357e99dab4a59155debcf353c6 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 17 Mar 2023 13:18:18 +0300 Subject: [PATCH 05/20] comment out include and verify page gets built --- msal/docs-ref-toc/fxtoc.yml | 2 +- msal/overview/{msal-react.md => react-getting-started.md} | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) rename msal/overview/{msal-react.md => react-getting-started.md} (93%) diff --git a/msal/docs-ref-toc/fxtoc.yml b/msal/docs-ref-toc/fxtoc.yml index 51377cf..854b557 100644 --- a/msal/docs-ref-toc/fxtoc.yml +++ b/msal/docs-ref-toc/fxtoc.yml @@ -2,6 +2,6 @@ uid: msal.sdk.landingPage.reference landingPageType: Root expanded: true - href: ~/overview/msal-react.md + href: ~/overview/react-getting-started.md children: - '**' \ No newline at end of file diff --git a/msal/overview/msal-react.md b/msal/overview/react-getting-started.md similarity index 93% rename from msal/overview/msal-react.md rename to msal/overview/react-getting-started.md index 6845510..e14e5ec 100644 --- a/msal/overview/msal-react.md +++ b/msal/overview/react-getting-started.md @@ -17,4 +17,9 @@ ms.author: dmwendia # Getting started with MSAL React -[!INCLUDE[MSAL React getting started](~/msal-react/docs/getting-started.md)] \ No newline at end of file + + From 6e89e404d8b4957182aa4308958a78ac04dae524 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 17 Mar 2023 13:27:02 +0300 Subject: [PATCH 06/20] maybe this will work --- msal/overview/react-getting-started.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/msal/overview/react-getting-started.md b/msal/overview/react-getting-started.md index e14e5ec..9b19e14 100644 --- a/msal/overview/react-getting-started.md +++ b/msal/overview/react-getting-started.md @@ -23,3 +23,8 @@ ms.author: dmwendia --> +[Link to docs.md](https://github.com/AzureAD/microsoft-authentication-library-for-js/lib/msal-react/docs/getting-started.md) + + + +[!INCLUDE[MSAL React](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md)] From 7f31e7ea14a176be82b446aaac732a3e0454c40a Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 21:53:02 +0300 Subject: [PATCH 07/20] update to msal browser --- msal/docs-ref-toc/fxtoc.yml | 8 +- msal/msal-browser/acquire-token.md | 116 +++++++++++++++++ msal/msal-browser/initialization.md | 27 ++++ msal/msal-browser/login-user.md | 165 +++++++++++++++++++++++++ msal/msal-browser/v1-migration.md | 127 +++++++++++++++++++ msal/msal-browser/v2-migration.md | 81 ++++++++++++ msal/overview/react-getting-started.md | 30 ----- 7 files changed, 522 insertions(+), 32 deletions(-) create mode 100644 msal/msal-browser/acquire-token.md create mode 100644 msal/msal-browser/initialization.md create mode 100644 msal/msal-browser/login-user.md create mode 100644 msal/msal-browser/v1-migration.md create mode 100644 msal/msal-browser/v2-migration.md delete mode 100644 msal/overview/react-getting-started.md diff --git a/msal/docs-ref-toc/fxtoc.yml b/msal/docs-ref-toc/fxtoc.yml index 854b557..aace33c 100644 --- a/msal/docs-ref-toc/fxtoc.yml +++ b/msal/docs-ref-toc/fxtoc.yml @@ -2,6 +2,10 @@ uid: msal.sdk.landingPage.reference landingPageType: Root expanded: true - href: ~/overview/react-getting-started.md + href: ~/overview/msal-overview.md children: - - '**' \ No newline at end of file + - '**' +- name: MSAL Browser + items: + - name: Initialization of MSAL + href: ~/msal-browser/initialization.md \ No newline at end of file diff --git a/msal/msal-browser/acquire-token.md b/msal/msal-browser/acquire-token.md new file mode 100644 index 0000000..3122960 --- /dev/null +++ b/msal/msal-browser/acquire-token.md @@ -0,0 +1,116 @@ +# Acquiring and Using an Access Token + +> :information_source: Before you start here, make sure you understand how to [initialize the application object](./initialization.md). It is also crucial to understand the relationship between [access tokens and resources](./resources-and-scopes.md). + +In MSAL, you can get access tokens for the APIs your app needs to call using the `acquireToken*` methods provided by the library. The `acquireToken*` methods abstract away the 2 steps involved in acquiring tokens with the [OAuth 2.0 authorization code flow](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow): + +1. make a request to Azure AD to obtain an `authorization code` +1. exchange that code for an [access token](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) containing the user consented scopes + +You can read more about access tokens [here](https://docs.microsoft.com/azure/active-directory/develop/access-tokens). + +## Acquiring an Access Token + +### Choose an Interaction Type + +See [here](./initialization.md#choosing-an-interaction-type) if you are uncertain about the differences between `acquireTokenRedirect` and `acquireTokenPopup`. + +### Prepare the request object + +You must pass a request object to the `acquireToken*` APIs. This object allows you to use different parameters in the request. See [here](./request-response-object.md) for more information on the request object parameters. Scopes are required for all `acquireToken*` calls. + +### Check the cache + +MSAL uses a [cache](./caching.md) to store tokens based on specific parameters including scopes, resource and authority, and will retrieve the token from the cache when needed. It also can perform silent renewal of those tokens when they have expired. MSAL exposes this functionality through the `acquireTokenSilent` method. + +After you've logged in with one of the `ssoSilent` or `login*` APIs the cache will contain a set of ID, access and refresh tokens. Every time you need an access token you should call `acquireTokenSilent` and if this fails call an interactive API instead. `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 using the cached refresh token. You can read more about using `acquireTokenSilent` [here](./token-lifetimes.md#token-renewal). + +#### Popup + +```javascript +var request = { + scopes: ["User.Read"], +}; + +msalInstance.acquireTokenSilent(request).then(tokenResponse => { + // Do something with the tokenResponse +}).catch(async (error) => { + if (error instanceof InteractionRequiredAuthError) { + // fallback to interaction when silent call fails + return msalInstance.acquireTokenPopup(request); + } + + // handle other errors +}) +``` + +#### Redirect + +```javascript +var request = { + scopes: ["User.Read"], +}; + +msalInstance.acquireTokenSilent(request).then(tokenResponse => { + // Do something with the tokenResponse +}).catch(error => { + if (error instanceof InteractionRequiredAuthError) { + // fallback to interaction when silent call fails + return msalInstance.acquireTokenRedirect(request) + } + + // handle other errors +}); +``` + +## Using the Access Token + +Once you have retrieved the access token, you must include it in the `Authorization` header as a [bearer token](https://www.rfc-editor.org/rfc/rfc6750) for the request to the resource you obtained the token for, as shown below: + +```JavaScript +var headers = new Headers(); +var bearer = "Bearer " + tokenResponse.accessToken; +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 + }); +``` + +## MSAL token acquisition best practices + +The following are best practices to acquire tokens with MSAL for avoiding errors, performance hits and usability issues. Certain scenarios may provide exceptions to these. + +### Use a single PublicClientApplication instance + +Instantiate one `PublicClientApplication` per application and use the same instance throughout your app. This ensures that there is a single source of truth for what MSAL is performing at any given time (see: [MSAL events](events.md)) and eliminates the chance of distinct app objects making parallel interactive requests or potential cache conflicts, which might break apps, reduce performance or hinder user experience. + +### Always wait for promises to resolve + +All MSAL `acquireToken*` as well as `login*` APIs perform asynchronous operations and return promises. You should always wait for these promises to resolve before doing any other tasks that depend on authentication state or tokens, such as rendering user information, calling a protected API or calling other MSAL APIs. + +### Attempt silent request first, then interactive + +When requesting tokens, always use `acquireTokenSilent` first, falling back to interactive token acquisition if needed (e.g., when the `InteractionRequiredAuthError` is thrown). + +Concurrent silent requests are permitted. If two or more silent requests are made concurrently, only one would go to the network (if needed), but all would receive the response, as long as those requests are for the same request parameters (e.g. scopes). + +Concurrent interactive requests are **not** permitted. If two or more interactive requests are made concurrently, only the first one will start an interaction, while the rest will fail with [interaction_in_progress](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/errors.md#interaction_in_progress) error. We recommend getting familiar with this error and possible remedies to avoid running into it in your applications. + +### Make one token request per resource + +You can only request access tokens for one resource at a time (see [resources and scopes](resources-and-scopes.md)). If needed, you can ask user consent to scopes (permissions) required by more than one resource by using the `extraScopesToConsent` parameter in the request object. Access tokens for previously consented scopes can be acquired silently. + +## Next Steps + +- [Token lifetimes, expiration and renewal](./token-lifetimes.md). +- [Caching in MSAL](./caching.md) +- [Handling errors](./errors.md) +- [Working with B2C](./working-with-b2c.md) +- [Throttling](../../msal-common/docs/Throttling.md) diff --git a/msal/msal-browser/initialization.md b/msal/msal-browser/initialization.md new file mode 100644 index 0000000..19b935b --- /dev/null +++ b/msal/msal-browser/initialization.md @@ -0,0 +1,27 @@ +--- +title: MSAL Browser +description: Getting started with MSAL React +services: active-directory +author: Dickson-Mwendia +manager: CelesteDG + +ms.service: active-directory +ms.subservice: develop +ms.topic: reference +ms.workload: identity +ms.date: 04/12/2023 +ms.author: dmwendia +--- + + +# Getting started with MSAL Browser + + + + + +[!INCLUDE[MSAL Browser](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md)] diff --git a/msal/msal-browser/login-user.md b/msal/msal-browser/login-user.md new file mode 100644 index 0000000..72fddfb --- /dev/null +++ b/msal/msal-browser/login-user.md @@ -0,0 +1,165 @@ +# Login User + +Before you start here, make sure you understand how to [initialize the application object](./initialization.md). + +The login APIs in MSAL retrieve an `authorization code` which can be exchanged for an [ID token](https://docs.microsoft.com/azure/active-directory/develop/id-tokens) for a signed in user, while consenting scopes for an additional resource, and 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. + +You can read more about ID tokens on our [Azure Docs pages](https://docs.microsoft.com/azure/active-directory/develop/id-tokens). + +## Choosing an Interaction Type + +See [here](./initialization.md#choosing-an-interaction-type) if you are uncertain about the differences between `loginRedirect` and `loginPopup`. + +## Login the user + +You must pass a request object to the login APIs. This object allows you to use different parameters in the request. See [here](./request-response-object.md) for more information on the request object parameters. + +For login requests, all parameters are optional, so you can just send an empty object. + +- Popup +```javascript +try { + const loginResponse = await msalInstance.loginPopup({}); +} catch (err) { + // handle error +} +``` + +- Redirect +```javascript +try { + msalInstance.loginRedirect({}); +} catch (err) { + // handle error +} +``` + +Or you can send a set of [scopes](./request-response-object.md#scopes) to pre-consent to: +- Popup +```javascript +var loginRequest = { + scopes: ["user.read", "mail.send"] // optional Array +}; + +try { + const loginResponse = await msalInstance.loginPopup(loginRequest); +} catch (err) { + // handle error +} +``` + +- Redirect +```javascript +var loginRequest = { + scopes: ["user.read", "mail.send"] // optional Array +}; + +try { + msalInstance.loginRedirect(loginRequest); +} catch (err) { + // handle error +} +``` + +## Account APIs + +When a login call has succeeded, you can use the `getAllAccounts()` function to retrieve information about currently signed in users. +```javascript +const myAccounts: AccountInfo[] = msalInstance.getAllAccounts(); +``` + +If you know the account information, you can also retrieve the account information by using the `getAccountByUsername()` or `getAccountByHomeId()` APIs: +```javascript +const username = "test@contoso.com"; +const myAccount: AccountInfo = msalInstance.getAccountByUsername(username); + +const homeAccountId = "userid.hometenantid"; // Best to retrieve the homeAccountId from an account object previously obtained through msal +const myAccount: AccountInfo = maslInstance.getAccountByHomeId(homeAccountId); +``` + +**Note:** `getAccountByUsername()` is provided for convenience and should be considered less reliable than `getAccountByHomeId()`. When possible use `getAccountByHomeId()`. + +In B2C scenarios your B2C tenant will need to be configured to return the `emails` claim on `idTokens` in order to use the `getAccountByUsername()` API. + +These APIs will return an account object or an array of account objects with the following signature: +```javascript +{ + // home account identifier for this account object + homeAccountId: string; + // Entity who issued the token represented as a full host of it (e.g. login.microsoftonline.com) + environment: string; + // Full tenant or organizational id that this account belongs to + tenantId: string; + // preferred_username claim of the id_token that represents this account. + username: string; +}; +``` + +## Silent login with ssoSilent() + +If you already have a session that exists with the authentication server, you can use the ssoSilent() API to make requests for tokens without interaction. + +### With User Hint + +If you already have the user's sign-in information, you can pass this into the API to improve performance and ensure that the authorization server will look for the correct account session. You can pass one of the following into the request object in order to successfully obtain a token silently. + +It is recommended to leverage the [`login_hint` optional ID token claim](https://docs.microsoft.com/azure/active-directory/develop/active-directory-optional-claims#v10-and-v20-optional-claims-set) (provided to `ssoSilent` as `loginHint`), as it is the most reliable account hint of silent (and interactive) requests. + +- `account` (which can be retrieved using on of the [account APIs](./accounts.md)) +- `sid` (which can be retrieved from the `idTokenClaims` of an `account` object) +- `login_hint` (which can be retrieved from either the account object `login_hint` ID token claim, `username` property, or the `upn` ID token claim) + +Passing an account will look for the `login_hint` optional ID token claim (preferred), then the `sid` optional id token claim, then fall back to `loginHint` (if provided) or account username. + +```javascript +const silentRequest = { + scopes: ["User.Read", "Mail.Read"], + loginHint: "user@contoso.com" +}; + +try { + const loginResponse = await msalInstance.ssoSilent(silentRequest); +} catch (err) { + if (err instanceof InteractionRequiredAuthError) { + const loginResponse = await msalInstance.loginPopup(silentRequest).catch(error => { + // handle error + }); + } else { + // handle error + } +} +``` + +### Without User Hint + +If there is not enough information available about the user, you can attempt to use the `ssoSilent` API **without** passing an `account`, `sid` or `login_hint`. + +```javascript +const silentRequest = { + scopes: ["User.Read", "Mail.Read"] +}; +``` + +However, be aware that if your application has code paths for multiple users in a single browser session, or if the user has multiple accounts for that single browser session, then there is a higher likelihood of silent sign-in errors. You may see the following error show up in the event of multiple account sessions found by the authorization server: + +```txt +InteractionRequiredAuthError: interaction_required: AADSTS16000: Either multiple user identities are available for the current request or selected account is not supported for the scenario. +``` + +This indicates that the server could not determine which account to sign into, and will require either one of the parameters above (`account`, `login_hint`, `sid`) or an interactive sign-in to choose the account. + +## RedirectUri Considerations + +When using popup and silent APIs we recommend setting the `redirectUri` to a blank page or a page that does not implement MSAL. This will help prevent potential issues as well as improve performance. If your application is only using popup and silent APIs you can set this on the `PublicClientApplication` config. If your application also needs to support redirect APIs you can set the `redirectUri` on a per request basis: + +Note: This does not apply for `loginRedirect` or `acquireTokenRedirect`. When using those APIs please see the directions on handling redirects [here](./initialization#redirect-apis) + +```javascript +msalInstance.loginPopup({ + redirectUri: "http://localhost:3000/blank.html" +}); +``` + +# Next Steps + +Learn how to [acquire and use an access token](./acquire-token.md)! diff --git a/msal/msal-browser/v1-migration.md b/msal/msal-browser/v1-migration.md new file mode 100644 index 0000000..fb70086 --- /dev/null +++ b/msal/msal-browser/v1-migration.md @@ -0,0 +1,127 @@ +# Migrating from MSAL 1.x to MSAL 2.x + +If you are new to MSAL, you should start [here](./initialization.md). + +If you are coming from [MSAL v1.x](../../msal-common/), you can follow this guide to update your code to use [MSAL v2.x](../../msal-browser/). + +## 1. Update application registration + +Go to the Azure AD portal for your tenant and review the App Registrations. You can create a [new registration](https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-app-registration#create-the-app-registration) for MSAL 2.x or you can [update your existing registration](https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-spa-app-registration#redirect-uri-msaljs-20-with-auth-code-flow) for the registration that you are using for MSAL 1.x. + +## 2. Add the msal-browser package to your project + +See the [installation section of the README](../README.md#installation). + +## 3. Update your code + +In MSAL 1.x, you created an application instance as below: + +```javascript +import * as msal from "msal"; + +const msalInstance = new msal.UserAgentApplication(config); +``` + +In MSAL 2.x, you can update this to use the new `PublicClientApplication` object. + +```javascript +import * as msal from "@azure/msal-browser"; + +const msalInstance = new msal.PublicClientApplication(config); +``` + +There may be some small differences in the configuration object that is passed in. If you are passing a more advanced configuration to the `UserAgentApplication` object, see [here](./configuration.md) for more information on new app object configuration options. + +Request and response object signatures have changed - `acquireTokenSilent` now has a separate object signature from the interactive APIs. Please see [here](./request-response-object.md) for more information on configuring the request APIs. + +Most APIs from MSAL 1.x have been carried forward to MSAL 2.x without change. Some functions have been removed: +- `handleRedirectCallback` +- `urlContainsHash` +- `getCurrentConfiguration` +- `getLoginInProgress` +- `getAccount` +- `getAccountState` +- `isCallback` + +In MSAL 2.x, handling the response from the hash is an asynchronous operation, as MSAL will perform a token exchange as soon as it parses the authorization code from the response. Because of this, when performing redirect calls, MSAL provides the `handleRedirectPromise` function which will return a promise that resolves when the redirect has been fully handled by MSAL. When using a redirect method, the page used as the `redirectUri` must implement `handleRedirectPromise` to ensure the response is handled and tokens are cached when returning from the redirect. + +```javascript +const myMSALObj = new msal.PublicClientApplication(msalConfig); + +// Register Callbacks for Redirect flow +myMSALObj.handleRedirectPromise().then((tokenResponse) => { + let accountObj = null; + if (tokenResponse !== null) { + accountObj = tokenResponse.account; + const id_token = tokenResponse.idToken; + const access_token = tokenResponse.accessToken; + } else { + const currentAccounts = myMSALObj.getAllAccounts(); + if (!currentAccounts || currentAccounts.length === 0) { + // No user signed in + return; + } else if (currentAccounts.length > 1) { + // More than one user signed in, find desired user with getAccountByUsername(username) + } else { + accountObj = currentAccounts[0]; + } + } + + const username = accountObj.username; + +}).catch((error) => { + handleError(error); +}); + +function signIn() { + myMSALObj.loginRedirect(loginRequest); +} + +async function getTokenRedirect(request) { + return await myMSALObj.acquireTokenSilent(request).catch(error => { + this.logger.info("silent token acquisition fails. acquiring token using redirect"); + // fallback to interaction when silent call fails + return myMSALObj.acquireTokenRedirect(request) + }); +} +``` + +During `loginPopup`, `acquireTokenPopup`, or `acquireTokenSilent` calls, you can wait for the promise to resolve. + +```javascript +const myMSALObj = new msal.PublicClientApplication(msalConfig); + +async function signIn(method) { + try { + const loginResponse = await myMSALObj.loginPopup(loginRequest); + } catch (err) { + handleError(error); + } + + const currentAccounts = myMSALObj.getAllAccounts(); + if (!currentAccounts || currentAccounts.length === 0) { + // No user signed in + return; + } else if (currentAccounts.length > 1) { + // More than one user signed in, find desired user with getAccountByUsername(username) + } else { + accountObj = currentAccounts[0]; + } +} + +async function getTokenPopup(request) { + return await myMSALObj.acquireTokenSilent(request).catch(async (error) => { + this.logger.info("silent token acquisition fails. acquiring token using popup"); + // fallback to interaction when silent call fails + return await myMSALObj.acquireTokenPopup(request).catch(error => { + handleError(error); + }); + }); +} +``` + +Please see the [login](./login-user.md) and [acquire token](./acquire-token.md) docs for more detailed information on usage. + +Refresh tokens are now returned as part of the token responses, and are used by the library to renew access tokens without interaction or the use of iframes. See the [token lifetimes docs](./token-lifetimes.md) for more information on renewing tokens. + +All other APIs should work as before. It is recommended to take a look at the [default sample](../../../samples/msal-browser-samples/VanillaJSTestApp2.0) to see a working example of MSAL 2.0. diff --git a/msal/msal-browser/v2-migration.md b/msal/msal-browser/v2-migration.md new file mode 100644 index 0000000..98aa16d --- /dev/null +++ b/msal/msal-browser/v2-migration.md @@ -0,0 +1,81 @@ +# Migrating from MSAL 2.x to MSAL 3.x + +If you are new to MSAL, you should start [here](initialization.md). + +If you are coming from [MSAL v1.x](../../msal-core/), you should check [this guide](v1-migration.md) first to migrate to [MSAL v2.x](../../msal-browser/) and then follow next steps. + +If you are coming from [MSAL v2.x](../../msal-browser/), you can follow this guide to update your code to use [MSAL v3.x](../../msal-browser/). + +## Update your code + +In MSAL v2.x, you created an application instance as below: + +```javascript +import * as msal from "@azure/msal-browser"; + +const msalConfig = { + auth: { + clientId: 'your_client_id' + } +}; + +const msalInstance = new msal.PublicClientApplication(msalConfig); +``` + +In MSAL v3.x, you must initialize the application object as well. There are several options at your disposal: + +### Option 1 + +Instantiate a `PublicClientApplication` object and initialize it afterwards. The `initialize` function is asynchronous and must resolve before invoking other MSAL.js APIs. + +```javascript +import * as msal from "@azure/msal-browser"; + +const msalConfig = { + auth: { + clientId: 'your_client_id' + } +}; + +const msalInstance = new msal.PublicClientApplication(msalConfig); +await msalInstance.initialize(); +``` + +### Option 2 + +Invoke the `createPublicClientApplication` static method which returns an initialized `PublicClientApplication` object. Note that this function is asynchronous. + +```javascript +import * as msal from "@azure/msal-browser"; + +const msalConfig = { + auth: { + clientId: 'your_client_id' + } +}; + +const msalInstance = await msal.PublicClientApplication.createPublicClientApplication(msalConfig); +``` + +All other APIs are backward compatible with [MSAL v2.x](../../msal-browser/). It is recommended to take a look at the [default sample](../../../samples/msal-browser-samples/VanillaJSTestApp2.0) to see a working example of MSAL v3.0. + +## Key changes + +### Browser support + +MSAL.js no longer supports the following browsers: + +- IE 11 +- Edge (Legacy) + +### Package dependencies + +Typescript version was bumped from `3.8.3` to `4.9.5`. + +### Compiler options + +Module/target versions were bumped from `es6`/`es5` to `es2020`/`es2020` respectively. + +### CDN + +MSAL.js is no longer hosted on a CDN. Check [this doc](cdn-usage.md) for more details. diff --git a/msal/overview/react-getting-started.md b/msal/overview/react-getting-started.md deleted file mode 100644 index 9b19e14..0000000 --- a/msal/overview/react-getting-started.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: MSAL React -description: Getting started with MSAL React -services: active-directory -author: Dickson-Mwendia -manager: CelesteDG - -ms.service: active-directory -ms.subservice: develop -ms.topic: reference -ms.workload: identity -ms.date: 01/10/2023 -ms.author: dmwendia ---- - - -# Getting started with MSAL React - - - - -[Link to docs.md](https://github.com/AzureAD/microsoft-authentication-library-for-js/lib/msal-react/docs/getting-started.md) - - - -[!INCLUDE[MSAL React](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md)] From 989a758457f2fc23f0f26b26cf1a2bc599fe172c Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 22:37:04 +0300 Subject: [PATCH 08/20] updates to fusion toc entries --- .openpublishing.publish.config.json | 2 +- msal/docfx.json | 7 +++++-- msal/docs-ref-toc/{fxtoc.yml => TOC.yml} | 0 3 files changed, 6 insertions(+), 3 deletions(-) rename msal/docs-ref-toc/{fxtoc.yml => TOC.yml} (100%) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 63868f7..6e868ba 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -54,7 +54,7 @@ "skip_source_output_uploading": false, "JoinTOCPlugin": [ { - "TopLevelTOC": "msal/docs-ref-toc/fxtoc.yml", + "TopLevelTOC": "msal/docs-ref-toc/TOC.yml", "ReferenceTOC": "msal/docs-ref-autogen/toc.yml", "ReferenceTOCUrl": "/javascript/api/microsoft-authentication-library-js/toc.json?view=msal-js-latest", "ConceptualTOCUrl": "/microsoft-authentication-library-js/toc.json", diff --git a/msal/docfx.json b/msal/docfx.json index 049d89d..3da4361 100644 --- a/msal/docfx.json +++ b/msal/docfx.json @@ -44,8 +44,11 @@ "files": [ "**/*.md" ], - "src": "overview", - "dest": "api/overview", + "src": [ + "overview", + "msal-browser" + ], + "dest": "api", "exclude": [], "version": "msal-js-latest" }, diff --git a/msal/docs-ref-toc/fxtoc.yml b/msal/docs-ref-toc/TOC.yml similarity index 100% rename from msal/docs-ref-toc/fxtoc.yml rename to msal/docs-ref-toc/TOC.yml From 16a6608789ce97e42597f969a722f0709cdeaa3d Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 22:51:08 +0300 Subject: [PATCH 09/20] updates TOC structure --- msal/docfx.json | 5 +---- msal/docs-ref-toc/TOC.yml | 14 +++++++------- msal/{overview => msal}/PackageStructure.png | Bin .../browser}/acquire-token.md | 0 .../browser}/initialization.md | 0 msal/{msal-browser => msal/browser}/login-user.md | 0 .../browser}/v1-migration.md | 0 .../browser}/v2-migration.md | 0 msal/{overview => msal}/msal-overview.md | 0 9 files changed, 8 insertions(+), 11 deletions(-) rename msal/{overview => msal}/PackageStructure.png (100%) rename msal/{msal-browser => msal/browser}/acquire-token.md (100%) rename msal/{msal-browser => msal/browser}/initialization.md (100%) rename msal/{msal-browser => msal/browser}/login-user.md (100%) rename msal/{msal-browser => msal/browser}/v1-migration.md (100%) rename msal/{msal-browser => msal/browser}/v2-migration.md (100%) rename msal/{overview => msal}/msal-overview.md (100%) diff --git a/msal/docfx.json b/msal/docfx.json index 3da4361..c4da2b5 100644 --- a/msal/docfx.json +++ b/msal/docfx.json @@ -44,10 +44,7 @@ "files": [ "**/*.md" ], - "src": [ - "overview", - "msal-browser" - ], + "src": "msal", "dest": "api", "exclude": [], "version": "msal-js-latest" diff --git a/msal/docs-ref-toc/TOC.yml b/msal/docs-ref-toc/TOC.yml index aace33c..5f30444 100644 --- a/msal/docs-ref-toc/TOC.yml +++ b/msal/docs-ref-toc/TOC.yml @@ -1,11 +1,11 @@ -- name: SDK reference - uid: msal.sdk.landingPage.reference - landingPageType: Root +- name: MSAL.js Overview expanded: true - href: ~/overview/msal-overview.md - children: - - '**' + href: ~/msal/msal-overview.md - name: MSAL Browser items: - name: Initialization of MSAL - href: ~/msal-browser/initialization.md \ No newline at end of file + href: ~/msal/browser/initialization.md + - name: Sign in users + href: ~/msal/browser/login-user.md + - name: Acquire tokens + href: ~/msal/browser/acquire-token.md \ No newline at end of file diff --git a/msal/overview/PackageStructure.png b/msal/msal/PackageStructure.png similarity index 100% rename from msal/overview/PackageStructure.png rename to msal/msal/PackageStructure.png diff --git a/msal/msal-browser/acquire-token.md b/msal/msal/browser/acquire-token.md similarity index 100% rename from msal/msal-browser/acquire-token.md rename to msal/msal/browser/acquire-token.md diff --git a/msal/msal-browser/initialization.md b/msal/msal/browser/initialization.md similarity index 100% rename from msal/msal-browser/initialization.md rename to msal/msal/browser/initialization.md diff --git a/msal/msal-browser/login-user.md b/msal/msal/browser/login-user.md similarity index 100% rename from msal/msal-browser/login-user.md rename to msal/msal/browser/login-user.md diff --git a/msal/msal-browser/v1-migration.md b/msal/msal/browser/v1-migration.md similarity index 100% rename from msal/msal-browser/v1-migration.md rename to msal/msal/browser/v1-migration.md diff --git a/msal/msal-browser/v2-migration.md b/msal/msal/browser/v2-migration.md similarity index 100% rename from msal/msal-browser/v2-migration.md rename to msal/msal/browser/v2-migration.md diff --git a/msal/overview/msal-overview.md b/msal/msal/msal-overview.md similarity index 100% rename from msal/overview/msal-overview.md rename to msal/msal/msal-overview.md From 856ff0c5ffab89ba13640115e76f0f03ee3a038e Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 23:00:16 +0300 Subject: [PATCH 10/20] update TOC schema --- .openpublishing.publish.config.json | 2 +- msal-javascript-conceptual/index.md | 8 ++++++++ msal/docs-ref-toc/{TOC.yml => fxtoc.yml} | 0 3 files changed, 9 insertions(+), 1 deletion(-) rename msal/docs-ref-toc/{TOC.yml => fxtoc.yml} (100%) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 6e868ba..63868f7 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -54,7 +54,7 @@ "skip_source_output_uploading": false, "JoinTOCPlugin": [ { - "TopLevelTOC": "msal/docs-ref-toc/TOC.yml", + "TopLevelTOC": "msal/docs-ref-toc/fxtoc.yml", "ReferenceTOC": "msal/docs-ref-autogen/toc.yml", "ReferenceTOCUrl": "/javascript/api/microsoft-authentication-library-js/toc.json?view=msal-js-latest", "ConceptualTOCUrl": "/microsoft-authentication-library-js/toc.json", diff --git a/msal-javascript-conceptual/index.md b/msal-javascript-conceptual/index.md index 04c787d..42dc4db 100644 --- a/msal-javascript-conceptual/index.md +++ b/msal-javascript-conceptual/index.md @@ -1 +1,9 @@ +--- +author: Dickson-Mwendia +ms.service: active-directory +ms.topic: include +ms.date: 04/12/2023 +ms.author: dmwendia +--- + # Welcome to msal-javascript-conceptual! \ No newline at end of file diff --git a/msal/docs-ref-toc/TOC.yml b/msal/docs-ref-toc/fxtoc.yml similarity index 100% rename from msal/docs-ref-toc/TOC.yml rename to msal/docs-ref-toc/fxtoc.yml From 05273032362049400f87ab3143a73450b7ced210 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 23:23:48 +0300 Subject: [PATCH 11/20] update dependent repo --- .openpublishing.publish.config.json | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 63868f7..1ae10fd 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -41,20 +41,12 @@ "sync_notification_subscribers": [], "branches_to_filter": [], "need_preview_pull_request": true, - "dependent_repositories": [ - { - "path_to_root": "_themes", - "url": "https://github.com/Microsoft/templates.docs.msft", - "branch": "main", - "branch_mapping": {} - } - ], "branch_target_mapping": {}, "docs_build_engine": {}, "skip_source_output_uploading": false, "JoinTOCPlugin": [ { - "TopLevelTOC": "msal/docs-ref-toc/fxtoc.yml", + "TopLevelTOC": "msal/docs-ref-toc/.yml", "ReferenceTOC": "msal/docs-ref-autogen/toc.yml", "ReferenceTOCUrl": "/javascript/api/microsoft-authentication-library-js/toc.json?view=msal-js-latest", "ConceptualTOCUrl": "/microsoft-authentication-library-js/toc.json", @@ -76,8 +68,8 @@ }, { "path_to_root": "lib", - "url": "https://github.com/AzureAD/microsoft-authentication-library-for-js", - "branch": "dev", + "url": "https://github.com/Dickson-Mwendia/microsoft-authentication-library-for-js", + "branch": "cross-repo-references-metadata", "branch_mapping": {} } ], From 99bdb29d31d0aa7bd359ea0f6e87c87f6bcc093b Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 23:30:35 +0300 Subject: [PATCH 12/20] update path to includes --- msal/msal/browser/initialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index 19b935b..68614b9 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -24,4 +24,4 @@ ms.author: dmwendia --> -[!INCLUDE[MSAL Browser](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md)] +[!INCLUDE[MSAL Browser](~/lib/msal-browser/docs/includes/initialization.md)] From 646d95b14eaa6396268cd421f6a7eb7eb3ce40c2 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Wed, 12 Apr 2023 23:48:17 +0300 Subject: [PATCH 13/20] update includes --- msal/msal/browser/acquire-token.md | 132 +++----------------- msal/msal/browser/initialization.md | 2 +- msal/msal/browser/login-user.md | 181 +++------------------------- 3 files changed, 33 insertions(+), 282 deletions(-) diff --git a/msal/msal/browser/acquire-token.md b/msal/msal/browser/acquire-token.md index 3122960..c2c7976 100644 --- a/msal/msal/browser/acquire-token.md +++ b/msal/msal/browser/acquire-token.md @@ -1,116 +1,16 @@ -# Acquiring and Using an Access Token - -> :information_source: Before you start here, make sure you understand how to [initialize the application object](./initialization.md). It is also crucial to understand the relationship between [access tokens and resources](./resources-and-scopes.md). - -In MSAL, you can get access tokens for the APIs your app needs to call using the `acquireToken*` methods provided by the library. The `acquireToken*` methods abstract away the 2 steps involved in acquiring tokens with the [OAuth 2.0 authorization code flow](https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow): - -1. make a request to Azure AD to obtain an `authorization code` -1. exchange that code for an [access token](https://docs.microsoft.com/azure/active-directory/develop/access-tokens) containing the user consented scopes - -You can read more about access tokens [here](https://docs.microsoft.com/azure/active-directory/develop/access-tokens). - -## Acquiring an Access Token - -### Choose an Interaction Type - -See [here](./initialization.md#choosing-an-interaction-type) if you are uncertain about the differences between `acquireTokenRedirect` and `acquireTokenPopup`. - -### Prepare the request object - -You must pass a request object to the `acquireToken*` APIs. This object allows you to use different parameters in the request. See [here](./request-response-object.md) for more information on the request object parameters. Scopes are required for all `acquireToken*` calls. - -### Check the cache - -MSAL uses a [cache](./caching.md) to store tokens based on specific parameters including scopes, resource and authority, and will retrieve the token from the cache when needed. It also can perform silent renewal of those tokens when they have expired. MSAL exposes this functionality through the `acquireTokenSilent` method. - -After you've logged in with one of the `ssoSilent` or `login*` APIs the cache will contain a set of ID, access and refresh tokens. Every time you need an access token you should call `acquireTokenSilent` and if this fails call an interactive API instead. `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 using the cached refresh token. You can read more about using `acquireTokenSilent` [here](./token-lifetimes.md#token-renewal). - -#### Popup - -```javascript -var request = { - scopes: ["User.Read"], -}; - -msalInstance.acquireTokenSilent(request).then(tokenResponse => { - // Do something with the tokenResponse -}).catch(async (error) => { - if (error instanceof InteractionRequiredAuthError) { - // fallback to interaction when silent call fails - return msalInstance.acquireTokenPopup(request); - } - - // handle other errors -}) -``` - -#### Redirect - -```javascript -var request = { - scopes: ["User.Read"], -}; - -msalInstance.acquireTokenSilent(request).then(tokenResponse => { - // Do something with the tokenResponse -}).catch(error => { - if (error instanceof InteractionRequiredAuthError) { - // fallback to interaction when silent call fails - return msalInstance.acquireTokenRedirect(request) - } - - // handle other errors -}); -``` - -## Using the Access Token - -Once you have retrieved the access token, you must include it in the `Authorization` header as a [bearer token](https://www.rfc-editor.org/rfc/rfc6750) for the request to the resource you obtained the token for, as shown below: - -```JavaScript -var headers = new Headers(); -var bearer = "Bearer " + tokenResponse.accessToken; -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 - }); -``` - -## MSAL token acquisition best practices - -The following are best practices to acquire tokens with MSAL for avoiding errors, performance hits and usability issues. Certain scenarios may provide exceptions to these. - -### Use a single PublicClientApplication instance - -Instantiate one `PublicClientApplication` per application and use the same instance throughout your app. This ensures that there is a single source of truth for what MSAL is performing at any given time (see: [MSAL events](events.md)) and eliminates the chance of distinct app objects making parallel interactive requests or potential cache conflicts, which might break apps, reduce performance or hinder user experience. - -### Always wait for promises to resolve - -All MSAL `acquireToken*` as well as `login*` APIs perform asynchronous operations and return promises. You should always wait for these promises to resolve before doing any other tasks that depend on authentication state or tokens, such as rendering user information, calling a protected API or calling other MSAL APIs. - -### Attempt silent request first, then interactive - -When requesting tokens, always use `acquireTokenSilent` first, falling back to interactive token acquisition if needed (e.g., when the `InteractionRequiredAuthError` is thrown). - -Concurrent silent requests are permitted. If two or more silent requests are made concurrently, only one would go to the network (if needed), but all would receive the response, as long as those requests are for the same request parameters (e.g. scopes). - -Concurrent interactive requests are **not** permitted. If two or more interactive requests are made concurrently, only the first one will start an interaction, while the rest will fail with [interaction_in_progress](https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/errors.md#interaction_in_progress) error. We recommend getting familiar with this error and possible remedies to avoid running into it in your applications. - -### Make one token request per resource - -You can only request access tokens for one resource at a time (see [resources and scopes](resources-and-scopes.md)). If needed, you can ask user consent to scopes (permissions) required by more than one resource by using the `extraScopesToConsent` parameter in the request object. Access tokens for previously consented scopes can be acquired silently. - -## Next Steps - -- [Token lifetimes, expiration and renewal](./token-lifetimes.md). -- [Caching in MSAL](./caching.md) -- [Handling errors](./errors.md) -- [Working with B2C](./working-with-b2c.md) -- [Throttling](../../msal-common/docs/Throttling.md) +--- +title: Acquire tokens in MSAL Browser +description: Acquire tokens in MSAL Browser +services: active-directory +author: Dickson-Mwendia +manager: CelesteDG + +ms.service: active-directory +ms.subservice: develop +ms.topic: reference +ms.workload: identity +ms.date: 04/12/2023 +ms.author: dmwendia +--- + +[!INCLUDE[MSAL Browser](~//msal-browser/docs/includes/acquire-token.md)] \ No newline at end of file diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index 68614b9..5cd7dbc 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -1,6 +1,6 @@ --- title: MSAL Browser -description: Getting started with MSAL React +description: Getting started with MSAL Browser services: active-directory author: Dickson-Mwendia manager: CelesteDG diff --git a/msal/msal/browser/login-user.md b/msal/msal/browser/login-user.md index 72fddfb..55bb5a3 100644 --- a/msal/msal/browser/login-user.md +++ b/msal/msal/browser/login-user.md @@ -1,165 +1,16 @@ -# Login User - -Before you start here, make sure you understand how to [initialize the application object](./initialization.md). - -The login APIs in MSAL retrieve an `authorization code` which can be exchanged for an [ID token](https://docs.microsoft.com/azure/active-directory/develop/id-tokens) for a signed in user, while consenting scopes for an additional resource, and 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. - -You can read more about ID tokens on our [Azure Docs pages](https://docs.microsoft.com/azure/active-directory/develop/id-tokens). - -## Choosing an Interaction Type - -See [here](./initialization.md#choosing-an-interaction-type) if you are uncertain about the differences between `loginRedirect` and `loginPopup`. - -## Login the user - -You must pass a request object to the login APIs. This object allows you to use different parameters in the request. See [here](./request-response-object.md) for more information on the request object parameters. - -For login requests, all parameters are optional, so you can just send an empty object. - -- Popup -```javascript -try { - const loginResponse = await msalInstance.loginPopup({}); -} catch (err) { - // handle error -} -``` - -- Redirect -```javascript -try { - msalInstance.loginRedirect({}); -} catch (err) { - // handle error -} -``` - -Or you can send a set of [scopes](./request-response-object.md#scopes) to pre-consent to: -- Popup -```javascript -var loginRequest = { - scopes: ["user.read", "mail.send"] // optional Array -}; - -try { - const loginResponse = await msalInstance.loginPopup(loginRequest); -} catch (err) { - // handle error -} -``` - -- Redirect -```javascript -var loginRequest = { - scopes: ["user.read", "mail.send"] // optional Array -}; - -try { - msalInstance.loginRedirect(loginRequest); -} catch (err) { - // handle error -} -``` - -## Account APIs - -When a login call has succeeded, you can use the `getAllAccounts()` function to retrieve information about currently signed in users. -```javascript -const myAccounts: AccountInfo[] = msalInstance.getAllAccounts(); -``` - -If you know the account information, you can also retrieve the account information by using the `getAccountByUsername()` or `getAccountByHomeId()` APIs: -```javascript -const username = "test@contoso.com"; -const myAccount: AccountInfo = msalInstance.getAccountByUsername(username); - -const homeAccountId = "userid.hometenantid"; // Best to retrieve the homeAccountId from an account object previously obtained through msal -const myAccount: AccountInfo = maslInstance.getAccountByHomeId(homeAccountId); -``` - -**Note:** `getAccountByUsername()` is provided for convenience and should be considered less reliable than `getAccountByHomeId()`. When possible use `getAccountByHomeId()`. - -In B2C scenarios your B2C tenant will need to be configured to return the `emails` claim on `idTokens` in order to use the `getAccountByUsername()` API. - -These APIs will return an account object or an array of account objects with the following signature: -```javascript -{ - // home account identifier for this account object - homeAccountId: string; - // Entity who issued the token represented as a full host of it (e.g. login.microsoftonline.com) - environment: string; - // Full tenant or organizational id that this account belongs to - tenantId: string; - // preferred_username claim of the id_token that represents this account. - username: string; -}; -``` - -## Silent login with ssoSilent() - -If you already have a session that exists with the authentication server, you can use the ssoSilent() API to make requests for tokens without interaction. - -### With User Hint - -If you already have the user's sign-in information, you can pass this into the API to improve performance and ensure that the authorization server will look for the correct account session. You can pass one of the following into the request object in order to successfully obtain a token silently. - -It is recommended to leverage the [`login_hint` optional ID token claim](https://docs.microsoft.com/azure/active-directory/develop/active-directory-optional-claims#v10-and-v20-optional-claims-set) (provided to `ssoSilent` as `loginHint`), as it is the most reliable account hint of silent (and interactive) requests. - -- `account` (which can be retrieved using on of the [account APIs](./accounts.md)) -- `sid` (which can be retrieved from the `idTokenClaims` of an `account` object) -- `login_hint` (which can be retrieved from either the account object `login_hint` ID token claim, `username` property, or the `upn` ID token claim) - -Passing an account will look for the `login_hint` optional ID token claim (preferred), then the `sid` optional id token claim, then fall back to `loginHint` (if provided) or account username. - -```javascript -const silentRequest = { - scopes: ["User.Read", "Mail.Read"], - loginHint: "user@contoso.com" -}; - -try { - const loginResponse = await msalInstance.ssoSilent(silentRequest); -} catch (err) { - if (err instanceof InteractionRequiredAuthError) { - const loginResponse = await msalInstance.loginPopup(silentRequest).catch(error => { - // handle error - }); - } else { - // handle error - } -} -``` - -### Without User Hint - -If there is not enough information available about the user, you can attempt to use the `ssoSilent` API **without** passing an `account`, `sid` or `login_hint`. - -```javascript -const silentRequest = { - scopes: ["User.Read", "Mail.Read"] -}; -``` - -However, be aware that if your application has code paths for multiple users in a single browser session, or if the user has multiple accounts for that single browser session, then there is a higher likelihood of silent sign-in errors. You may see the following error show up in the event of multiple account sessions found by the authorization server: - -```txt -InteractionRequiredAuthError: interaction_required: AADSTS16000: Either multiple user identities are available for the current request or selected account is not supported for the scenario. -``` - -This indicates that the server could not determine which account to sign into, and will require either one of the parameters above (`account`, `login_hint`, `sid`) or an interactive sign-in to choose the account. - -## RedirectUri Considerations - -When using popup and silent APIs we recommend setting the `redirectUri` to a blank page or a page that does not implement MSAL. This will help prevent potential issues as well as improve performance. If your application is only using popup and silent APIs you can set this on the `PublicClientApplication` config. If your application also needs to support redirect APIs you can set the `redirectUri` on a per request basis: - -Note: This does not apply for `loginRedirect` or `acquireTokenRedirect`. When using those APIs please see the directions on handling redirects [here](./initialization#redirect-apis) - -```javascript -msalInstance.loginPopup({ - redirectUri: "http://localhost:3000/blank.html" -}); -``` - -# Next Steps - -Learn how to [acquire and use an access token](./acquire-token.md)! +--- +title: Sign in users in MSAL Browser +description: Sign in users in MSAL Browser +services: active-directory +author: Dickson-Mwendia +manager: CelesteDG + +ms.service: active-directory +ms.subservice: develop +ms.topic: reference +ms.workload: identity +ms.date: 04/12/2023 +ms.author: dmwendia +--- + +[!INCLUDE[Sign in users](~/msal-browser/docs/includes/login-user.md)] \ No newline at end of file From b16ca95be85ab83b21eb3c0d3ff68ec5ab003124 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Thu, 13 Apr 2023 00:07:19 +0300 Subject: [PATCH 14/20] update include pathys --- .openpublishing.publish.config.json | 2 +- msal/msal/browser/acquire-token.md | 2 +- msal/msal/browser/login-user.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 1ae10fd..afd36b2 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -67,7 +67,7 @@ "branch_mapping": {} }, { - "path_to_root": "lib", + "path_to_root": "microsoft-authentication-library-for-js", "url": "https://github.com/Dickson-Mwendia/microsoft-authentication-library-for-js", "branch": "cross-repo-references-metadata", "branch_mapping": {} diff --git a/msal/msal/browser/acquire-token.md b/msal/msal/browser/acquire-token.md index c2c7976..8f63df4 100644 --- a/msal/msal/browser/acquire-token.md +++ b/msal/msal/browser/acquire-token.md @@ -13,4 +13,4 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -[!INCLUDE[MSAL Browser](~//msal-browser/docs/includes/acquire-token.md)] \ No newline at end of file +[!INCLUDE[MSAL Browser](~/lib/msal-browser/docs/includes/acquire-token.md)] \ No newline at end of file diff --git a/msal/msal/browser/login-user.md b/msal/msal/browser/login-user.md index 55bb5a3..2d2bad3 100644 --- a/msal/msal/browser/login-user.md +++ b/msal/msal/browser/login-user.md @@ -13,4 +13,4 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -[!INCLUDE[Sign in users](~/msal-browser/docs/includes/login-user.md)] \ No newline at end of file +[!INCLUDE[Sign in users](~/microsoft-authentication-library-for-js/lib/msal-browser/docs/includes/login-user.md)] \ No newline at end of file From fde1c6942823af97ac2fbc3b12325e9a76c7838d Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Thu, 13 Apr 2023 16:59:46 +0300 Subject: [PATCH 15/20] test crr --- .openpublishing.publish.config.json | 2 +- msal/msal/browser/acquire-token.md | 2 +- msal/msal/browser/initialization.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index afd36b2..1ae10fd 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -67,7 +67,7 @@ "branch_mapping": {} }, { - "path_to_root": "microsoft-authentication-library-for-js", + "path_to_root": "lib", "url": "https://github.com/Dickson-Mwendia/microsoft-authentication-library-for-js", "branch": "cross-repo-references-metadata", "branch_mapping": {} diff --git a/msal/msal/browser/acquire-token.md b/msal/msal/browser/acquire-token.md index 8f63df4..b51b6ff 100644 --- a/msal/msal/browser/acquire-token.md +++ b/msal/msal/browser/acquire-token.md @@ -13,4 +13,4 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -[!INCLUDE[MSAL Browser](~/lib/msal-browser/docs/includes/acquire-token.md)] \ No newline at end of file +[!INCLUDE[MSAL Browser token acquisition](~/msal-browser/docs/includes/acquire-token.md)] \ No newline at end of file diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index 5cd7dbc..a5ca8a9 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -24,4 +24,4 @@ ms.author: dmwendia --> -[!INCLUDE[MSAL Browser](~/lib/msal-browser/docs/includes/initialization.md)] +[!INCLUDE[MSAL Browser initialization](~/lib/msal-browser/docs/includes/initialization.md)] From 15c3abee568fdbd8cf572cfef8ef287ad94a45ee Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 14 Apr 2023 09:57:23 +0300 Subject: [PATCH 16/20] update includes syntax --- msal/msal/browser/acquire-token.md | 2 +- msal/msal/browser/initialization.md | 2 +- msal/msal/browser/login-user.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/msal/msal/browser/acquire-token.md b/msal/msal/browser/acquire-token.md index b51b6ff..09100b1 100644 --- a/msal/msal/browser/acquire-token.md +++ b/msal/msal/browser/acquire-token.md @@ -13,4 +13,4 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -[!INCLUDE[MSAL Browser token acquisition](~/msal-browser/docs/includes/acquire-token.md)] \ No newline at end of file +[!INCLUDE[MSAL Browser token acquisition](/../msal-browser/docs/includes/acquire-token.md)] diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index a5ca8a9..7d3d288 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -24,4 +24,4 @@ ms.author: dmwendia --> -[!INCLUDE[MSAL Browser initialization](~/lib/msal-browser/docs/includes/initialization.md)] +[!INCLUDE[MSAL Browser initialization](/lib/msal-browser/docs/includes/initialization.md)] diff --git a/msal/msal/browser/login-user.md b/msal/msal/browser/login-user.md index 2d2bad3..f8685b2 100644 --- a/msal/msal/browser/login-user.md +++ b/msal/msal/browser/login-user.md @@ -13,4 +13,4 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -[!INCLUDE[Sign in users](~/microsoft-authentication-library-for-js/lib/msal-browser/docs/includes/login-user.md)] \ No newline at end of file +[!INCLUDE[Sign in users](msal-browser/docs/includes/login-user.md)] \ No newline at end of file From 5007556dd9032d35db5e00c1bf2dac4ae5a8147e Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 14 Apr 2023 10:11:52 +0300 Subject: [PATCH 17/20] update docfx.json --- msal-javascript-conceptual/docfx.json | 1 + msal/msal/browser/initialization.md | 3 +++ 2 files changed, 4 insertions(+) diff --git a/msal-javascript-conceptual/docfx.json b/msal-javascript-conceptual/docfx.json index 78cd05d..5ed2f36 100644 --- a/msal-javascript-conceptual/docfx.json +++ b/msal-javascript-conceptual/docfx.json @@ -18,6 +18,7 @@ "LICENSE-CODE", "ThirdPartyNotices.md", "SECURITY.md" + "lib/**" ] } ], diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index 7d3d288..962dfc8 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -24,4 +24,7 @@ ms.author: dmwendia --> +[!INCLUDE[MSAL Browser initialization](/lib/msal-browser/docs/includes/initialization.md)] + + [!INCLUDE[MSAL Browser initialization](/lib/msal-browser/docs/includes/initialization.md)] From aa9b93c0d3dfd35d2282cbe8bfa5d9ebba36dd0d Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 14 Apr 2023 10:28:39 +0300 Subject: [PATCH 18/20] try fixing includes --- msal-javascript-conceptual/index.md | 5 ++++- msal/msal/browser/initialization.md | 10 ---------- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/msal-javascript-conceptual/index.md b/msal-javascript-conceptual/index.md index 42dc4db..da799ca 100644 --- a/msal-javascript-conceptual/index.md +++ b/msal-javascript-conceptual/index.md @@ -6,4 +6,7 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -# Welcome to msal-javascript-conceptual! \ No newline at end of file +# Welcome to msal-javascript-conceptual! + + +J \ No newline at end of file diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index 962dfc8..b7ba480 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -17,14 +17,4 @@ ms.author: dmwendia # Getting started with MSAL Browser - - - -[!INCLUDE[MSAL Browser initialization](/lib/msal-browser/docs/includes/initialization.md)] - - [!INCLUDE[MSAL Browser initialization](/lib/msal-browser/docs/includes/initialization.md)] From 4bd4bb63b1f203ffa0188ebbe8b0ff9af891858f Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 14 Apr 2023 10:47:13 +0300 Subject: [PATCH 19/20] include path syntax --- msal/msal/browser/acquire-token.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/msal/msal/browser/acquire-token.md b/msal/msal/browser/acquire-token.md index 09100b1..113e9bc 100644 --- a/msal/msal/browser/acquire-token.md +++ b/msal/msal/browser/acquire-token.md @@ -13,4 +13,4 @@ ms.date: 04/12/2023 ms.author: dmwendia --- -[!INCLUDE[MSAL Browser token acquisition](/../msal-browser/docs/includes/acquire-token.md)] +[!INCLUDE[MSAL Browser token acquisition](~/../lib/msal-browser/docs/includes/acquire-token.md)] From 508467eb168d7865de74a26f9d38a4acfbfbc736 Mon Sep 17 00:00:00 2001 From: Dickson Mwendia <64727760+Dickson-Mwendia@users.noreply.github.com> Date: Fri, 14 Apr 2023 11:54:39 +0300 Subject: [PATCH 20/20] update crr repo --- .openpublishing.publish.config.json | 4 ++-- msal/msal/browser/initialization.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.openpublishing.publish.config.json b/.openpublishing.publish.config.json index 1ae10fd..5f7ee0f 100644 --- a/.openpublishing.publish.config.json +++ b/.openpublishing.publish.config.json @@ -68,8 +68,8 @@ }, { "path_to_root": "lib", - "url": "https://github.com/Dickson-Mwendia/microsoft-authentication-library-for-js", - "branch": "cross-repo-references-metadata", + "url": "https://github.com/AzureAD/microsoft-authentication-library-for-js", + "branch": "test-cross-repo-reference", "branch_mapping": {} } ], diff --git a/msal/msal/browser/initialization.md b/msal/msal/browser/initialization.md index b7ba480..423b49f 100644 --- a/msal/msal/browser/initialization.md +++ b/msal/msal/browser/initialization.md @@ -17,4 +17,4 @@ ms.author: dmwendia # Getting started with MSAL Browser -[!INCLUDE[MSAL Browser initialization](/lib/msal-browser/docs/includes/initialization.md)] +[!INCLUDE[MSAL Browser initialization](~/../../lib/msal-browser/docs/includes/initialization.md)]