Skip to content

Commit b73f3dc

Browse files
authored
Merge pull request #105913 from ktoliver/public-48702
[PUBLIC_MOVE] commit from public PR 48702
2 parents 25b0289 + a8b3abf commit b73f3dc

File tree

1 file changed

+69
-61
lines changed

1 file changed

+69
-61
lines changed

articles/active-directory/develop/quickstart-v2-javascript.md

Lines changed: 69 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Sign in users in JavaScript single-page apps | Azure
33
titleSuffix: Microsoft identity platform
4-
description: Learn how a Javascript app can an API that requires access tokens using the Microsoft identity platform.
4+
description: Learn how a JavaScript app can call an API that requires access tokens using the Microsoft identity platform.
55
services: active-directory
66
author: navyasric
77
manager: CelesteDG
@@ -26,7 +26,7 @@ In this quickstart, you use a code sample to learn how a JavaScript single-page
2626

2727
* Azure subscription - [create one for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F)
2828
* [Node.js](https://nodejs.org/en/download/).
29-
* Either [Visual Studio Code](https://code.visualstudio.com/download) (to edit project files), or [Visual Studio 2019](https://visualstudio.microsoft.com/downloads/) (ro run the project as a Visual Studio Solution).
29+
* [Visual Studio Code](https://code.visualstudio.com/download) (to edit project files)
3030

3131
> [!div renderon="docs"]
3232
> ## Register and download your quickstart application
@@ -37,7 +37,9 @@ In this quickstart, you use a code sample to learn how a JavaScript single-page
3737
> 1. Sign in to the [Azure portal](https://portal.azure.com) by using either a work or school account, or a personal Microsoft account.
3838
> 1. If your account gives you access to more than one tenant, select the account at the top right, and then set your portal session to the Azure Active Directory (Azure AD) tenant you want to use.
3939
> 1. Go to the new [Azure portal - App registrations](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade/quickStartType/JavascriptSpaQuickstartPage/sourceType/docs) pane.
40-
> 1. Enter a name for your application, and select **Register**.
40+
> 1. Enter a name for your application.
41+
> 1. Under **Supported account types**, select **Accounts in any organizational directory and personal Microsoft accounts**.
42+
> 1. Select **Register**.
4143
> 1. Follow the instructions to download and automatically configure your new application.
4244
>
4345
> ### Option 2 (Manual): Register and manually configure your application and code sample
@@ -51,15 +53,15 @@ In this quickstart, you use a code sample to learn how a JavaScript single-page
5153
> 1. Select **New registration**.
5254
> 1. When the **Register an application** page appears, enter a name for your application.
5355
> 1. Under **Supported account types**, select **Accounts in any organizational directory and personal Microsoft accounts**.
54-
> 1. Under the **Redirect URI** section, in the drop-down list, select the **Web** platform, and then set the value to `http://localhost:30662/`.
5556
> 1. Select **Register**. On the app **Overview** page, note the **Application (client) ID** value for later use.
5657
> 1. This quickstart requires the [Implicit grant flow](v2-oauth2-implicit-grant-flow.md) to be enabled. In the left pane of the registered application, select **Authentication**.
57-
> 1. In the **Advanced settings** section, under **Implicit grant**, select the **ID tokens** and **Access tokens** check boxes. ID tokens and access tokens are required, because this app needs to sign in users and call an API.
58-
> 1. At the top of the pane, select **Save**.
58+
> 1. Under **Platform Configurations**, select **Add a platform**. A panel opens on the left. There, select the **Web Applications** region.
59+
> 1. Still on the left, set the **Redirect URI** value to `http://localhost:3000/`. Then, select **Access Token** and **ID Token**.
60+
> 1. Select **Configure**.
5961
6062
> [!div class="sxs-lookup" renderon="portal"]
6163
> #### Step 1: Configure your application in the Azure portal
62-
> For the code sample for this quickstart to work, you need to add a `redirectUri` as `http://localhost:30662/` and enable **Implicit grant**.
64+
> To make the code sample in this quickstart work, you need to add a `redirectUri` as `http://localhost:3000/` and enable **Implicit grant**.
6365
> > [!div renderon="portal" id="makechanges" class="nextstepaction"]
6466
> > [Make these changes for me]()
6567
>
@@ -72,39 +74,40 @@ Select the option that's suitable to your development environment:
7274

7375
* To run the project with a web server by using Node.js, [download the core project files](https://github.com/Azure-Samples/active-directory-javascript-graphapi-v2/archive/quickstart.zip). To open the files, use an editor such as [Visual Studio Code](https://code.visualstudio.com/).
7476

75-
* (Optional) To run the project with the IIS server, [download the Visual Studio project](https://github.com/Azure-Samples/active-directory-javascript-graphapi-v2/archive/vsquickstart.zip). Extract the zip file to a local folder (for example, *C:\Azure-Samples*).
76-
7777
#### Step 3: Configure your JavaScript app
7878

7979
> [!div renderon="docs"]
80-
> In the *JavaScriptSPA* folder, edit *index.html*, and set the `clientID` and `authority` values under `msalConfig`.
80+
> In the *JavaScriptSPA* folder, edit *authConfig.js*, and set the `clientID` and `authority` values under `msalConfig`.
8181
8282
> [!div class="sxs-lookup" renderon="portal"]
83-
> In the *JavaScriptSPA* folder, edit *index.html*, and replace `msalConfig` with the following code:
83+
> In the *JavaScriptSPA* folder, edit *authConfig.js*, and replace `msalConfig` with the following code:
8484
8585
```javascript
86-
var msalConfig = {
86+
87+
// Config object to be passed to Msal on creation
88+
const msalConfig = {
8789
auth: {
88-
clientId: "Enter_the_Application_Id_here",
89-
authority: "https://login.microsoftonline.com/Enter_the_Tenant_info_here",
90-
redirectUri: "http://localhost:30662/"
90+
clientId: "Enter_the_Application_Id_Here",
91+
authority: "Enter_the_Cloud_Instance_Id_HereEnter_the_Tenant_Info_Here",
92+
redirectUri: "Enter_the_Redirect_Uri_Here",
9193
},
9294
cache: {
93-
cacheLocation: "localStorage",
94-
storeAuthStateInCookie: true
95+
cacheLocation: "sessionStorage", // This configures where your cache will be stored
96+
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
97+
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new
9598
}
96-
};
99+
};
97100

98101
```
99102
> [!div renderon="portal"]
100103
> > [!NOTE]
101104
> > This quickstart supports Enter_the_Supported_Account_Info_Here.
102105
103-
104106
> [!div renderon="docs"]
105107
>
106108
> Where:
107-
> - *\<Enter_the_Application_Id_here>* is the **Application (client) ID** for the application you registered.
109+
> - *\<Enter_the_Application_Id_Here>* is the **Application (client) ID** for the application you registered.
110+
> - *\<Enter_the_Cloud_Instance_Id_Here>* is the instance of the Azure cloud. For the main or global Azure cloud, simply enter *https://login.microsoftonline.com*. For **national** clouds (for example, China), see [National clouds](https://docs.microsoft.com/azure/active-directory/develop/authentication-national-cloud).
108111
> - *\<Enter_the_Tenant_info_here>* is set to one of the following options:
109112
> - If your application supports *accounts in this organizational directory*, replace this value with the **Tenant ID** or **Tenant name** (for example, *contoso.microsoft.com*).
110113
> - If your application supports *accounts in any organizational directory*, replace this value with **organizations**.
@@ -116,20 +119,17 @@ var msalConfig = {
116119
117120
#### Step 4: Run the project
118121

119-
* If you're using [Node.js](https://nodejs.org/en/download/):
120-
121-
1. To start the server, run the following command from the project directory:
122-
123-
```batch
124-
npm install
125-
node server.js
126-
```
122+
If you're using [Node.js](https://nodejs.org/en/download/):
127123

128-
1. Open a web browser and go to `http://localhost:30662/`.
129-
1. Select **Sign In** to start the sign-in, and then call Microsoft Graph API.
124+
1. To start the server, run the following command from the project directory:
130125

126+
```batch
127+
npm install
128+
npm start
129+
```
131130

132-
* If you're using [Visual Studio](https://visualstudio.microsoft.com/downloads/), select the project solution, and then select F5 to run the project.
131+
1. Open a web browser and go to `http://localhost:3000/`.
132+
1. Select **Sign In** to start the sign-in, and then call Microsoft Graph API.
133133

134134
After the browser loads the application, select **Sign In**. The first time that you sign in, you're prompted to provide your consent to allow the application to access your profile and to sign you in. After you're signed in successfully, your user profile information should be displayed on the page.
135135

@@ -144,7 +144,7 @@ After the browser loads the application, select **Sign In**. The first time that
144144
The MSAL library signs in users and requests the tokens that are used to access an API that's protected by Microsoft identity platform. The quickstart *index.html* file contains a reference to the library:
145145

146146
```html
147-
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/msal.min.js"></script>
147+
<script type="text/javascript" src="https://alcdn.msftauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>
148148
```
149149
> [!TIP]
150150
> You can replace the preceding version with the latest released version under [MSAL.js releases](https://github.com/AzureAD/microsoft-authentication-library-for-js/releases).
@@ -161,26 +161,28 @@ npm install msal
161161
The quickstart code also shows how to initialize the MSAL library:
162162

163163
```javascript
164-
var msalConfig = {
164+
// Config object to be passed to Msal on creation
165+
const msalConfig = {
165166
auth: {
166-
clientId: "Enter_the_Application_Id_here",
167-
authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
168-
redirectUri: "http://localhost:30662/"
167+
clientId: "75d84e7a-40bx-f0a2-91b9-0c82d4c556aa", // this is a fake id
168+
authority: "https://login.microsoftonline.com/common",
169+
redirectUri: "http://localhost:3000/",
169170
},
170171
cache: {
171-
cacheLocation: "localStorage",
172-
storeAuthStateInCookie: true
172+
cacheLocation: "sessionStorage", // This configures where your cache will be stored
173+
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
174+
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new
173175
}
174-
};
176+
};
175177

176-
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
178+
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
177179
```
178180

179181
> |Where | |
180182
> |---------|---------|
181183
> |`clientId` | The application ID of the application that's registered in the Azure portal.|
182184
> |`authority` | (Optional) The authority URL that supports account types, as described previously in the configuration section. The default authority is `https://login.microsoftonline.com/common`. |
183-
> |`redirectUri` | The application registration's configured reply/redirectUri. In this case, `http://localhost:30662/`. |
185+
> |`redirectUri` | The application registration's configured reply/redirectUri. In this case, `http://localhost:3000/`. |
184186
> |`cacheLocation` | (Optional) Sets the browser storage for the auth state. The default is sessionStorage. |
185187
> |`storeAuthStateInCookie` | (Optional) The library that stores the authentication request state that's required for validation of the authentication flows in the browser cookies. This cookie is set for IE and Edge browsers to mitigate certain [known issues](https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/Known-issues-on-IE-and-Edge-Browser#issues). |
186188
@@ -191,11 +193,13 @@ For more information about available configurable options, see [Initialize clien
191193
The following code snippet shows how to sign in users:
192194

193195
```javascript
194-
var requestObj = {
195-
scopes: ["user.read"]
196+
// Add scopes for the id token to be used at Microsoft identity platform endpoints.
197+
const loginRequest = {
198+
scopes: ["openid", "profile", "User.Read"],
196199
};
197200

198-
myMSALObj.loginPopup(requestObj).then(function (loginResponse) {
201+
myMSALObj.loginPopup(loginRequest)
202+
.then((loginResponse) => {
199203
//Login Success callback code here
200204
}).catch(function (error) {
201205
console.log(error);
@@ -218,21 +222,23 @@ MSAL uses three methods to acquire tokens: `acquireTokenRedirect`, `acquireToken
218222
The `acquireTokenSilent` method handles token acquisitions and renewal without any user interaction. After the `loginRedirect` or `loginPopup` method is executed for the first time, `acquireTokenSilent` is the method commonly used to obtain tokens that are used to access protected resources for subsequent calls. Calls to request or renew tokens are made silently.
219223

220224
```javascript
221-
var requestObj = {
222-
scopes: ["user.read"]
225+
// Add scopes for the access token to be used at Microsoft Graph API endpoints.
226+
const tokenRequest = {
227+
scopes: ["Mail.Read"]
223228
};
224229

225-
myMSALObj.acquireTokenSilent(requestObj).then(function (tokenResponse) {
226-
// Callback code here
227-
console.log(tokenResponse.accessToken);
228-
}).catch(function (error) {
229-
console.log(error);
230-
});
230+
myMSALObj.acquireTokenSilent(tokenRequest)
231+
.then((tokenResponse) => {
232+
// Callback code here
233+
console.log(tokenResponse.accessToken);
234+
}).catch((error) => {
235+
console.log(error);
236+
});
231237
```
232238

233239
> |Where | |
234240
> |---------|---------|
235-
> | `scopes` | Contains scopes being requested to be returned in the access token for API. For example, `[ "user.read" ]` for Microsoft Graph or `[ "<Application ID URL>/scope" ]` for custom Web APIs (that is, `api://<Application ID>/access_as_user`).|
241+
> | `scopes` | Contains scopes being requested to be returned in the access token for API. For example, `[ "mail.read" ]` for Microsoft Graph or `[ "<Application ID URL>/scope" ]` for custom Web APIs (that is, `api://<Application ID>/access_as_user`).|
236242
237243
#### Get a user token interactively
238244

@@ -246,16 +252,18 @@ The usual recommended pattern for most applications is to call `acquireTokenSile
246252
Calling the `acquireTokenPopup` results in a popup window for signing in. (Or `acquireTokenRedirect` results in redirecting users to the Microsoft identity platform endpoint.) In that window, users need to interact by confirming their credentials, giving the consent to the required resource, or completing the two-factor authentication.
247253

248254
```javascript
249-
var requestObj = {
250-
scopes: ["user.read"]
255+
// Add here scopes for access token to be used at MS Graph API endpoints.
256+
const tokenRequest = {
257+
scopes: ["Mail.Read"]
251258
};
252259

253-
myMSALObj.acquireTokenPopup(requestObj).then(function (tokenResponse) {
254-
// Callback code here
255-
console.log(tokenResponse.accessToken);
256-
}).catch(function (error) {
257-
console.log(error);
258-
});
260+
myMSALObj.acquireTokenPopup(requestObj)
261+
.then((tokenResponse) => {
262+
// Callback code here
263+
console.log(tokenResponse.accessToken);
264+
}).catch((error) => {
265+
console.log(error);
266+
});
259267
```
260268

261269
> [!NOTE]

0 commit comments

Comments
 (0)