Skip to content

Commit 025285b

Browse files
committed
Rewrite code samples README
1 parent f46c7d3 commit 025285b

1 file changed

Lines changed: 149 additions & 57 deletions

File tree

1-Authentication/5-sign-in-express/README.md

Lines changed: 149 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -186,45 +186,65 @@ Although many applications can be associated with your user flow, a single appli
186186
187187
1. Choose **Select**.
188188
189-
190-
191-
192189
## Clone or download sample web application
193190
194-
From your shell or command line:
191+
To get the web app sample code, [Download the .zip file](https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial/archive/refs/heads/main.zip) or clone the sample web application from GitHub by running the following command:
195192
196193
```console
197194
git clone https://github.com/Azure-Samples/ms-identity-ciam-javascript-tutorial.git
198195
```
199196

197+
If you choose to download the *.zip* file, extract the sample app file to a folder where the total length of the path is 260 or fewer characters.
200198

201-
### Step 2: Install project dependencies
199+
## Install project dependencies
200+
201+
1. Open a console window, and change to the directory that contains the Node.js sample app:
202202

203203
```console
204204
cd 1-Authentication\5-sign-in-express\App
205-
npm install
206205
```
207206

208-
209-
### Step 4: Running the sample
207+
1. Run the following commands to install app dependencies:
210208

211209
```console
212-
cd 1-Authentication\5-sign-in-express\App
213-
npm start
210+
npm install
214211
```
215212

216-
## Configure the client app (ciam-msal-node-webapp) to use your app registration
213+
## Configure the sample web app to use your app registration
214+
215+
1. In your code editor, open *App\authConfig.js* file.
217216

217+
1. Find the placeholder:
218+
219+
1. `Enter_the_Application_Id_Here` and replace it with the Application (client) ID of the app you registered earlier.
220+
221+
1. `Enter_the_Tenant_Subdomain_Here` and replace it with the Directory (tenant) subdomain. For example, if your tenant primary domain is `contoso.onmicrosoft.com`, use `contoso`. If you don't have your tenant name, learn how to [read your tenant details](https://learn.microsoft.com/entra/external-id/customers/how-to-create-customer-tenant-portal#get-the-customer-tenant-details).
222+
223+
1. `Enter_the_Client_Secret_Here` and replace it with the app secret value you copied earlier.
218224

219-
## Explore the sample
225+
## Run and test sample web app
220226

221-
1. Open your browser and navigate to `http://localhost:3000`.
222-
1. Select the **Sign In** link.
223-
1. Select the **View ID token claims** link to see the claims in your ID token.
227+
You can now test the sample Node.js web app. You need to start the Node.js server and access it through your browser at `http://localhost:3000`.
224228

225-
![Screenshot](./ReadmeFiles/screenshot.png)
229+
1. In your terminal, run the following command:
226230

227-
> :information_source: Did the sample not work for you as expected? Then please reach out to us using the [GitHub Issues](../../../../issues) page.
231+
```console
232+
npm start
233+
```
234+
235+
1. Open your browser, then go to http://localhost:3000.
236+
237+
1. After the page completes loading, select **Sign in** link. You're prompted to sign in.
238+
239+
1. On the sign-in page, type your **Email address**, select **Next**, type your **Password**, then select **Sign in**. If you don't have an account, select **No account? Create one** link, which starts the sign-up flow.
240+
241+
1. If you choose the sign-up option, after filling in your email, one-time passcode, new password and more account details, you complete the whole sign-up flow. You see a page similar to the following screenshot. You see a similar page if you choose the sign-in option.
242+
243+
![Screenshot](./ReadmeFiles/screenshot.png)
244+
245+
1. Select **Sign out** to sign the user out of the web app or select **View ID token claims** to view ID token claims returned by Microsoft Entra.
246+
247+
> :information_source: If the sample didn't work for you as expected, reach out to us using the [GitHub Issues](../../../../issues) page.
228248

229249
## We'd love your feedback!
230250

@@ -235,61 +255,136 @@ Were we successful in addressing your learning objective? Consider taking a mome
235255
<details>
236256
<summary>Expand for troubleshooting info</summary>
237257

238-
> * Use [Stack Overflow](http://stackoverflow.com/questions/tagged/msal) to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
239-
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
240-
Make sure that your questions or comments are tagged with [`azure-active-directory-b2c` `node` `ms-identity` `adal` `msal-js` `msal`].
258+
> * Use [Stack Overflow](http://stackoverflow.com/questions/tagged/msal) to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [`azure-active-directory-b2c` `node` `ms-identity` `adal` `msal-js` `msal`].
241259

242-
To provide feedback on or suggest features for Azure Active Directory, visit [User Voice page](https://feedback.azure.com/d365community/forum/79b1327d-d925-ec11-b6e6-000d3a4f06a4).
260+
To provide feedback on or suggest features for Microsoft Entra ID or Microsoft Entra External ID, visit [User Voice page](https://feedback.azure.com/d365community/forum/79b1327d-d925-ec11-b6e6-000d3a4f06a4).
243261
</details>
244262

245263
## About the code
246264

247265
### Initialization
248266

249-
// Explain how the app is configured
267+
In order to use MSAL Node, we instantiate the [ConfidentialClientApplication](https://learn.microsoft.com/javascript/api/@azure/msal-node/confidentialclientapplication?view=azure-node-latest):
250268

251-
### Sign-in
269+
1. Create the configuration object, `msalConfig`, as shown in the *App/authConfig.js* file:
252270

253-
// Explain how the app signs in users
271+
```javascript
272+
const msalConfig = {
273+
auth: {
274+
clientId: process.env.CLIENT_ID || 'Enter_the_Application_Id_Here', // 'Application (client) ID' of app registration in Microsoft Entra - this value is a GUID
275+
authority: process.env.AUTHORITY || `https://${TENANT_SUBDOMAIN}.ciamlogin.com/`, // Replace the placeholder with your tenant name
276+
clientSecret: process.env.CLIENT_SECRET || 'Enter_the_Client_Secret_Here', // Client secret generated from the app registration in Azure portal
277+
},
278+
...
279+
...
280+
};
281+
```
254282

255-
### Sign-out
283+
1. Use the `msalConfig` object to instantiate the confidential client application shown in the *App/auth/AuthProvider.js file (`AuthProvider` class):
284+
285+
```javascript
286+
...
287+
...
288+
getMsalInstance(msalConfig) {
289+
return new msal.ConfidentialClientApplication(msalConfig);
290+
}
291+
....
292+
...
293+
```
294+
295+
### Sign in
296+
297+
The first leg of auth code flow generates an authorization code request URL, then redirects to that URL to obtain the authorization code. This first leg is implemented in the `redirectToAuthCodeUrl` method. Notice how we use MSALs [getAuthCodeUrl](https://learn.microsoft.com/javascript/api/%40azure/msal-node/confidentialclientapplication?view=azure-node-latest#@azure-msal-node-confidentialclientapplication-getauthcodeurl) method to generate authorization code URL, then redirect to the authorization code URL itself:
256298

257-
To sing-out the current user, the app destroys the session that holds user data and navigates the browser to the Azure AD logout endpoint to end the session with Azure AD. This is shown in [auth.js](./App/routes/auth.js):
258299

259300
```javascript
301+
async redirectToAuthCodeUrl(req, res, next, authCodeUrlRequestParams, authCodeRequestParams, msalInstance) {
302+
...
303+
...
304+
305+
try {
306+
const authCodeUrlResponse = await msalInstance.getAuthCodeUrl(req.session.authCodeUrlRequest);
307+
res.redirect(authCodeUrlResponse);
308+
} catch (error) {
309+
next(error);
310+
}
311+
}
312+
```
313+
314+
In the second leg of auth code flow uses, use the authorization code to request an ID token by using MSAL's [acquireTokenByCode]() method. You can store the ID token and user account information in an express session.
315+
316+
```javascript
317+
async handleRedirect(req, res, next) {
318+
const authCodeRequest = {
319+
...req.session.authCodeRequest,
320+
code: req.body.code, // authZ code
321+
...
322+
};
323+
324+
try {
325+
const msalInstance = this.getMsalInstance(this.config.msalConfig);
326+
msalInstance.getTokenCache().deserialize(req.session.tokenCache);
327+
328+
const tokenResponse = await msalInstance.acquireTokenByCode(authCodeRequest, req.body);
329+
330+
req.session.tokenCache = msalInstance.getTokenCache().serialize();
331+
req.session.idToken = tokenResponse.idToken;
332+
req.session.account = tokenResponse.account;
333+
req.session.isAuthenticated = true;
334+
...
335+
...
336+
} catch (error) {
337+
next(error);
338+
}
339+
}
340+
```
341+
342+
### Sign out
343+
344+
When you want to sign the user out of the application, it isn't enough to end the user's session. You must redirect the user to the `logoutUri`. Otherwise, the user might be able to reauthenticate to your applications without reentering their credentials. If the name of your tenant is contoso, then the logoutUri looks similar to `https://contoso.ciamlogin.com/contoso.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=http://localhost:3000`.
345+
346+
```javascript
347+
async logout(req, res, next) {
348+
/**
349+
* Construct a logout URI and redirect the user to end the session with Microsoft Entra ID.
350+
*/
351+
const logoutUri = `${this.config.msalConfig.auth.authority}${TENANT_SUBDOMAIN}.onmicrosoft.com/oauth2/v2.0/logout?post_logout_redirect_uri=${this.config.postLogoutRedirectUri}`;
352+
353+
req.session.destroy(() => {
354+
res.redirect(logoutUri);
355+
});
356+
}
260357
```
261358

262359
### Deploying Web app to Azure App Service
263360

264361
There is one web app in this sample. To deploy it to **Azure App Services**, you'll need to:
265362

266-
- create an **Azure App Service**
267-
- publish the projects to the **App Services**, and
268-
- update its client(s) to call the website instead of the local environment.
363+
- Create an **Azure App Service**
364+
- Publish the projects to the **App Services**, and
365+
- Update its client(s) to call the website instead of the local environment.
269366

270-
> :information_source: If you would like to use **VS Code Azure Tools** extension for deployment, [watch the tutorial](https://docs.microsoft.com/azure/developer/javascript/tutorial-vscode-azure-app-service-node-01) offered by Microsoft Docs.
271367

272-
#### Deploy your files (ciam-msal-node-webapp)
368+
#### Deploy your files of your web app
273369

274-
1. In the **VS Code** activity bar, select the **Azure** logo to show the **Azure App Service** explorer. Select **Sign in to Azure...** and follow the instructions. Once signed in, the explorer should show the name of your **Azure** subscription(s).
275-
2. On the **App Service** explorer section you will see an upward-facing arrow icon. Click on it publish your local files in the project folder to **Azure App Services** (use "Browse" option if needed, and locate the right folder).
276-
3. Choose a creation option based on the operating system to which you want to deploy. in this sample, we choose **Linux**.
277-
4. Select a **Node.js** version when prompted. An **LTS** version is recommended.
278-
5. Type a globally unique name for your web app and press Enter. The name must be unique across all of **Azure**. (e.g. `ciam-msal-node-webapp`)
279-
6. After you respond to all the prompts, **VS Code** shows the **Azure** resources that are being created for your app in its notification popup.
280-
7. Select **Yes** when prompted to update your configuration to run `npm install` on the target **Linux** server.
370+
1. In the **VS Code** activity bar, select the **Azure** logo to show the **Azure App Service** explorer.
371+
1. Select **Sign in to Azure...**, then follow the instructions. Once signed in, the explorer should show the name of your **Azure** subscription(s).
372+
1. On the **App Service** explorer section you see an upward-facing arrow icon. Select it publish your local files in the project folder to **Azure App Services** (use "Browse" option if needed, and locate the right folder).
373+
1. Choose a creation option based on the operating system to which you want to deploy. In this sample, we illustrate by using the **Linux** option.
374+
1. Select a **Node.js** version when prompted. We recommend a **LTS** version.
375+
1. Type a globally unique name for your web app and select **Enter**. The name must be unique across all of **Azure** services. After you respond to all the prompts, **VS Code** shows the **Azure** resources that are being created for your app in its notification popup.
376+
1. Select **Yes** when prompted to update your configuration. This action runs `npm install` on the target **Linux** server.
281377

282-
#### Update the CIAM app registration (ciam-msal-node-webapp)
378+
#### Update the CIAM app registration to use hosted version
283379

284-
1. Navigate back to to the [Azure portal](https://portal.azure.com).
285-
In the left-hand navigation pane, select the **Azure Active Directory** service, and then select **App registrations (Preview)**.
286-
1. In the resulting screen, select the `ciam-msal-node-webapp` application.
287-
1. In the app's registration screen, select **Authentication** in the menu.
288-
1. In the **Redirect URIs** section, update the reply URLs to match the site URL of your Azure deployment. For example:
289-
1. `https://ciam-msal-node-webapp.azurewebsites.net`
290-
1. `https://ciam-msal-node-webapp.azurewebsites.net/auth/redirect`
380+
1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least an [Application Developer](https://learn.microsoft.com/entra/identity/role-based-access-control/permissions-reference#application-developer).
381+
1. Browse to **Identity** >**Applications** > **App registrations**.
382+
1. From the app registration list, select the app that you want to update.
383+
1. Under **Manage**, select **Authentication**.
384+
1. Update your **Redirect URIs** to to match the site URL of your Azure deployment such as `https://ciam-msal-node-webapp.azurewebsites.net/auth/redirect`.
385+
1. Select **Configure** to save your changes.
291386

292-
> :warning: If your app is using an *in-memory* storage, **Azure App Services** will spin down your web site if it is inactive, and any records that your app was keeping will be empty. In addition, if you increase the instance count of your website, requests will be distributed among the instances. Your app's records, therefore, will not be the same on each instance.
387+
> :warning: If your app use *in-memory* storage, **Azure App Services** will spin down your web site if it is inactive. This action empties any records in the memory. In addition, if you increase the instance count of your website, Azure Service distributes the requests among the instances. Therefore, rour app's records won't be the same on each instance.
293388
</details>
294389
295390
## Contributing
@@ -300,14 +395,11 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope
300395

301396
## Learn More
302397

303-
* [Customize the default branding](https://github.com/microsoft/entra-previews/blob/PP2/docs/5-Customize-default-branding.md)
304-
* [OAuth 2.0 device authorization grant flow](https://github.com/microsoft/entra-previews/blob/PP2/docs/9-OAuth2-device-code.md)
305-
* [Customize sign-in strings](https://github.com/microsoft/entra-previews/blob/PP2/docs/8-Customize-sign-in-strings.md)
398+
* [Customize the default branding](https://learn.microsoft.com/entra/external-id/customers/how-to-customize-branding-customers)
399+
* [Language customize](https://learn.microsoft.com/entra/external-id/customers/how-to-customize-languages-customers)
306400
* [Building Zero Trust ready apps](https://aka.ms/ztdevsession)
307-
* [Initialize client applications using MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-initializing-client-applications)
308-
* [Single sign-on with MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-sso)
309-
* [Handle MSAL.js exceptions and errors](https://docs.microsoft.com/azure/active-directory/develop/msal-handling-exceptions?tabs=javascript)
310-
* [Logging in MSAL.js applications](https://docs.microsoft.com/azure/active-directory/develop/msal-logging?tabs=javascript)
311-
* [Pass custom state in authentication requests using MSAL.js](https://docs.microsoft.com/azure/active-directory/develop/msal-js-pass-custom-state-authentication-request)
312-
* [Prompt behavior in MSAL.js interactive requests](https://docs.microsoft.com/azure/active-directory/develop/msal-js-prompt-behavior)
313-
* [Use MSAL.js to work with Azure AD B2C](https://docs.microsoft.com/azure/active-directory/develop/msal-b2c-overview)
401+
* [Initialize client applications using MSAL.js](https://learn.microsoft.com/entra/identity-platform/msal-js-initializing-client-applications)
402+
* [Single sign-on with MSAL.js](https://learn.microsoft.com/entra/identity-platform/msal-js-sso)
403+
* [Handle MSAL.js exceptions and errors](https://learn.microsoft.com/entra/msal/dotnet/advanced/exceptions/msal-error-handling?tabs=javascript)
404+
* [Logging in MSAL.js applications](https://learn.microsoft.com/entra/msal/dotnet/advanced/exceptions/msal-logging?tabs=javascript)
405+
* [Pass custom state in authentication requests using MSAL.js](https://learn.microsoft.com/entra/identity-platform/msal-js-pass-custom-state-authentication-request)

0 commit comments

Comments
 (0)