### Install and Start Node.js Server Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/vanillajs-spa/README.md Installs project dependencies and starts the Node.js development server. Run these commands from within the project directory. ```bash npm install npm start ``` -------------------------------- ### HTTP GET Request Example Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md Example of an HTTP GET request to the /api/greeting endpoint, including the Authorization header with a Bearer token. ```http GET /api/greeting HTTP/1.1 Host: myfunction.azurewebsites.net Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc... ``` -------------------------------- ### Example Client Requests for Protected Endpoint Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/api-protection.md Demonstrates how to make requests to a protected endpoint. The first example shows a valid request, while the comments indicate expected responses for invalid or unauthorized requests. ```bash # Valid request with required scope curl -H "Authorization: Bearer {accessToken}" http://localhost:8080/ # Returns 403 if token lacks Greeting.Read scope # Returns 401 if token is invalid or missing ``` -------------------------------- ### Express Setup for Client Credentials Flow Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/msal-node.md Basic Express setup for client credentials flow. This snippet demonstrates how to initialize msal-node and acquire a token for API calls using application identity. ```javascript const express = require('express'); const msal = require('@azure/msal-node'); const https = require('https'); const msalConfidentialClientApp = new msal.ConfidentialClientApplication(msalConfig); const app = express(); app.get('/api/application', (req, res) => { msalConfidentialClientApp.acquireTokenByClientCredential(tokenRequest) .then((response) => { // Use token in API call }) .catch((error) => { /* error handling */ }); }); app.listen(8080, () => console.log('Listening at http://localhost:8080/')); ``` -------------------------------- ### Initialize MSAL and MsalProvider Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/react-spa.md Example of initializing the PublicClientApplication with msalConfig and wrapping the React application with MsalProvider. ```javascript import { msalConfig } from './authConfig'; import { PublicClientApplication } from '@azure/msal-browser'; import { MsalProvider } from '@azure/msal-react'; const msalInstance = new PublicClientApplication(msalConfig); // Use in React application ``` -------------------------------- ### Success Response Example Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md Example of a successful 200 OK response from the /api/greeting endpoint. ```text Hello, world. You were able to access this because you provided a valid access token with the Greeting.Read scope as a claim. ``` -------------------------------- ### Example Login Request Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/react-spa.md An example of a login request object specifying the 'User.Read' scope for Microsoft Graph. ```javascript import { loginRequest } from './authConfig'; const loginRequest = { scopes: ["User.Read"] }; ``` -------------------------------- ### Run the Node.js Application Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/protect-api/README.md Execute this command in your terminal to start the Node.js application. ```bash node app.js ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/angular-spa/README.md Install the necessary npm packages for your Angular project. ```bash npm install ``` -------------------------------- ### Error Response Example (Invalid Token) Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md Example of a 403 Forbidden response when the provided token is invalid. ```text Invalid token. ``` -------------------------------- ### Call Protected API with Access Token Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/protected-api-access-protected-api/README.md Issue an HTTP GET request to the '/me' endpoint with an 'Authorization' header containing a Bearer token. This example uses curl. ```console $ curl http://localhost:8080/me -H "Authorization: Bearer {VALID-ACCESS-TOKEN}" { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity", "businessPhones": ["+1 (999) 5551001"], "displayName": "Contoso Employee", "givenName": "Contoso", "jobTitle": "Worker", "mail": "cemployee@contoso.com", "mobilePhone": "1 999-555-1001", "officeLocation": "Contoso Plaza/F30", "preferredLanguage": null, "surname": "Employee", "userPrincipalName": "contoso_employee@contoso.com", "id": "00aa00aa-bb11-cc22-dd33-44ee44ee" } ``` -------------------------------- ### MSAL Configuration Example Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/vanillajs-spa/README.md Configure MSAL.js by providing your application's client ID, authority, and redirect URI. Adjust the `authority` for different account types or national clouds. ```javascript const msalConfig = { auth: { clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply. authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here', redirectUri: 'Enter_the_Redirect_URI_Here/', }, ``` -------------------------------- ### Error Response Example (Insufficient Scope) Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md Example of a 403 Forbidden response when the provided token lacks the required scope. ```text Missing required scope. ``` -------------------------------- ### Initiate Sign-In Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Starts the user sign-in flow using either a popup window or a full-page redirect. Note that IE forces redirect regardless of the chosen method. ```javascript // Start login with popup await signIn("popup"); // Or start login with redirect await signIn("redirect"); ``` -------------------------------- ### MsalGuardConfiguration Example Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/types.md Configure the route guard to enforce authentication. Specify interaction type and authentication request with required scopes. ```typescript const config: MsalGuardConfiguration = { interactionType: InteractionType.Redirect, authRequest: { scopes: ['user.read'] } }; ``` -------------------------------- ### Example Graph API Endpoint Usage Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/react-spa.md Demonstrates how to access the Microsoft Graph API endpoint URL from the graphConfig object. ```javascript import { graphConfig } from './authConfig'; const apiUrl = graphConfig.graphMeEndpoint; // "https://graph.microsoft.com/v1.0/me" ``` -------------------------------- ### Example Client Request with Curl Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md This bash script demonstrates how to obtain an access token using curl and then use it to call a protected endpoint. It requires a tenant ID, client ID, user credentials, and the scope for the target API. ```bash # Get access token first TOKEN=$(curl -X POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token \ -d 'client_id={clientId}' \ -d 'scope=https://api.example.com/.default' \ -d 'grant_type=password' \ -d 'username={user}' \ -d 'password={password}' | jq -r '.access_token') # Call protected endpoint curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/ ``` -------------------------------- ### MsalInterceptorConfiguration Example Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/types.md Configure the HTTP interceptor to attach tokens to requests. Specify interaction type and map protected resources to scopes. ```typescript const config: MsalInterceptorConfiguration = { interactionType: InteractionType.Redirect, protectedResourceMap: new Map([ ['https://graph.microsoft.com/v1.0/me', ['user.read']], ['https://api.example.com/data', ['api.read']] ]) }; ``` -------------------------------- ### Express JWT Validation Setup Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/api-protection.md Configuration object for tenant and audience used in JWT validation for Express applications. ```APIDOC ## JWT Validation Configuration ### Express JWT Validation Setup **Source:** `protect-api/app.js:15` Configuration object for tenant and audience used in JWT validation. ```javascript const config = { auth: { tenant: string, audience: string } } ``` **Properties:** | Property | Type | Required | Description | |----------|------|----------|-------------| | auth.tenant | string | Yes | Azure AD Tenant ID (Directory ID) - GUID from app registration | | auth.audience | string | Yes | Azure AD Application (client) ID of the API app registration - GUID | **Example:** ```javascript const config = { auth: { tenant: 'Enter_the_Tenant_ID_Here', audience: 'Enter_the_Application_Id_Here' } }; ``` ``` -------------------------------- ### Example Client Request for User Token and API Call Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md This bash script demonstrates how a client application can obtain a user access token with the 'user_impersonation' scope and then use that token to call the protected API's /me endpoint. It uses curl for token acquisition and API invocation. ```bash # Step 1: Client gets token with user_impersonation scope USER_TOKEN=$(curl -X POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token \ -d 'client_id={clientId}' \ -d 'scope=api://{apiAppId}/user_impersonation' \ -d 'grant_type=password' \ -d 'username={user}' \ -d 'password={password}' | jq -r '.access_token') # Step 2: Call API endpoint with user token curl -H "Authorization: Bearer $USER_TOKEN" http://localhost:8080/me ``` -------------------------------- ### Express Setup for On-Behalf-Of Flow Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/msal-node.md Express setup for API-to-API on-behalf-of flow with JWT validation. This snippet includes middleware for JWT validation and scope checking to secure API endpoints. ```javascript const express = require('express'); const { expressjwt: jwt } = require("express-jwt"); const jwks = require('jwks-rsa'); const jwtAuthz = require('express-jwt-authz'); const msal = require('@azure/msal-node'); const app = express(); // JWT validation middleware app.use(jwt({ secret: jwks.expressJwtSecret({ jwksUri: config.auth.authority + '/discovery/v2.0/keys' }), audience: config.auth.clientId, issuer: config.auth.authority + '/v2.0', algorithms: ['RS256'] })); // Scope validation middleware app.get('/me', jwtAuthz(['user_impersonation'], { customScopeKey: 'scp', customUserKey: 'auth' }), (req, res) => { /* route handler */ }); app.listen(8080, () => console.log('Listening at http://localhost:8080/')); ``` -------------------------------- ### GET / Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md Greeting endpoint protected by JWT access token validation and scope authorization. Requires a valid JWT Bearer token with the 'Greeting.Read' scope. ```APIDOC ## GET / ### Description Greeting endpoint protected by JWT access token validation and scope authorization. ### Method GET ### Endpoint / ### Parameters #### Request Headers - **Authorization** (string) - Required - `Bearer {accessToken}` - Valid JWT access token with Greeting.Read scope ### Request Example ```http GET / HTTP/1.1 Host: localhost:8080 Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc... ``` ### Response #### Success Response (200) - **body** (string) - "Hello, world. You were able to access this because you provided a valid access token with the Greeting.Read scope as a claim." #### Response Example ```json Hello, world. You were able to access this because you provided a valid access token with the Greeting.Read scope as a claim. ``` ### Error Handling #### Status Codes - **200** - Valid token with Greeting.Read scope - **401** - Missing, invalid, or expired access token - **403** - Valid token but missing Greeting.Read scope #### Error Response (401 - Invalid Token) ```json { "error": "UnauthorizedError", "message": "invalid_token", "status": 401 } ``` #### Error Response (403 - Insufficient Scope) ```json { "error": "Insufficient permissions", "required_scope": "Greeting.Read", "status": 403 } ``` ``` -------------------------------- ### HTTP GET Request for Application Info Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md This is the HTTP request format to retrieve application details from the /api/application endpoint. ```http GET /api/application HTTP/1.1 Host: localhost:8080 ``` -------------------------------- ### Subscribe to Token Acquisition Success Event Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/types.md This example demonstrates how to subscribe to the ACQUIRE_TOKEN_SUCCESS event using RxJS operators. It logs the expiration time of the acquired token. ```javascript import { EventType } from '@azure/msal-browser'; msalBroadcastService.msalSubject$ .pipe(filter(msg => msg.eventType === EventType.ACQUIRE_TOKEN_SUCCESS)) .subscribe(msg => { const result = msg.payload as AuthenticationResult; console.log('Token acquired, expires:', result.expiresOn); }); ``` -------------------------------- ### Configure Application using PowerShell Script Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/vanillajs-spa/README.md Run this PowerShell script to automatically register your Microsoft Entra ID application and configure the sample application's code. Ensure PowerShell 7 or later is installed. This script can optionally take TenantId and AzureEnvironmentName as parameters. ```powershell cd .\AppCreationScripts\ .\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'" ``` -------------------------------- ### Initiate Sign-Out Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Starts the user sign-out flow using either a popup window or a full-page redirect. The page is reloaded after a popup logout, and the user is redirected after a redirect logout. ```javascript // Logout with popup signOut("popup"); // Logout with full-page redirect signOut("redirect"); ``` -------------------------------- ### Express Server Setup with JWT Middleware Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/api-protection.md This code sets up an Express server with `express-jwt` middleware for validating JWTs and `jwks-rsa` for fetching signing keys. It configures the audience, issuer, and algorithms for token validation. ```javascript const express = require('express'); const { expressjwt: jwt } = require("express-jwt"); const jwks = require('jwks-rsa'); const jwtAuthz = require('express-jwt-authz'); const config = { auth: { tenant: 'Enter_the_Tenant_ID_Here', audience: 'Enter_the_Application_Id_Here' } }; const app = express(); app.use(jwt({ secret: jwks.expressJwtSecret({ jwksUri: 'https://login.microsoftonline.com/' + config.auth.tenant + '/discovery/v2.0/keys' }), audience: config.auth.audience, issuer: 'https://login.microsoftonline.com/' + config.auth.tenant + '/v2.0', algorithms: ['RS256'] })); app.get('/', jwtAuthz(['Greeting.Read'], { customScopeKey: 'scp', customUserKey: 'auth' }), (req, res) => { res.send('Hello, world. You were able to access this because you provided a ' + 'valid access token with the Greeting.Read scope as a claim.'); } ); app.listen(8080, () => console.log('Listening at http://localhost:8080')); ``` -------------------------------- ### Call Microsoft Graph API using Client Credentials Flow Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/msal-client-credentials-flow/README.md This example shows the output of a curl request to the Node.js API, which in turn calls Microsoft Graph using the client credentials flow. The response displays application details fetched from Microsoft Graph. ```console $ curl http://localhost:8080/api/application { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#applications/$entity", "id": "00aa00aa-bb11-cc22-dd33-44ee44ee44ee", "deletedDateTime": null, "appId": "00001111-aaaa-2222-bbbb-3333cccc4444", "applicationTemplateId": null, "disabledByMicrosoftStatus": null, "createdDateTime": "2021-12-17T16:45:43Z", "displayName": "Node Web API", "description": null, "groupMembershipClaims": null, "identifierUris": [], "isDeviceOnlyAuthSupported": null, "isFallbackPublicClient": true, "notes": null, "publisherDomain": "contoso.onmicrosoft.com", "serviceManagementReference": null, "signInAudience": "AzureADMyOrg", "tags": [], "tokenEncryptionKeyId": null, "defaultRedirectUri": null, "certification": null, "optionalClaims": null ... } ``` -------------------------------- ### Clone the Sample Application using Git Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/vanillajs-spa/README.md Use this command to clone the sample application repository from GitHub to your local machine. ```console git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript ``` -------------------------------- ### Initialize MSAL and MsalProvider in React App Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/react-spa.md This snippet shows the main entry point of a React SPA. It initializes the MSAL public client application with the provided configuration and wraps the root App component with MsalProvider. This makes the MSAL instance accessible to all child components via React Context. ```javascript import { PublicClientApplication } from '@azure/msal-browser'; import { MsalProvider } from '@ किसी/msal-react'; import { msalConfig } from './authConfig'; const msalInstance = new PublicClientApplication(msalConfig); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); ``` -------------------------------- ### Initialize MSAL and Handle Redirect Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Initializes the MSAL PublicClientApplication and sets up the handling of OAuth redirect responses. This is typically done when the application loads. ```javascript const myMSALObj = new msal.PublicClientApplication(msalConfig); myMSALObj.initialize().then(() => { myMSALObj.handleRedirectPromise() .then(handleResponse) .catch(err => console.error(err)); }); ``` -------------------------------- ### PublicClientApplication Full Configuration Object Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/configuration.md This object defines all available configuration options for the PublicClientApplication. It includes settings for authentication, caching, and logging. ```javascript { auth: { clientId: string, authority: string, redirectUri: string, navigateToLoginRequestUrl?: boolean, postLogoutRedirectUri?: string }, cache: { cacheLocation: "sessionStorage" | "localStorage", storeAuthStateInCookie?: boolean }, system: { loggerOptions: { loggerCallback: (level: LogLevel, message: string, containsPii: boolean) => void, piiLoggingEnabled?: boolean, logLevel?: LogLevel } } } ``` -------------------------------- ### Create MSAL PublicClientApplication Instance Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/angular-spa.md Factory function to create and return a configured PublicClientApplication instance. It sets up authentication client ID, authority, redirect URI, and cache location. ```typescript import { MSALInstanceFactory } from './app.module'; const msalInstance = MSALInstanceFactory(); ``` -------------------------------- ### Run Angular Application Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/angular-spa/README.md Use this command to serve the Angular application locally and automatically open it in your default web browser. Follow the on-screen instructions for authentication. ```console ng serve --open ``` -------------------------------- ### Get Account Username and Name Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/types.md Retrieve the username and display name from an AccountInfo object. This is useful for displaying user information after authentication. ```javascript const account = myMSALObj.getActiveAccount(); console.log(account.username); // "user@example.com" console.log(account.name); // "John Doe" console.log(account.homeAccountId); // "oid-guid.tid-guid" ``` -------------------------------- ### Select User Account Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Retrieves the current user account from MSAL. Use this to get the active account or to check if any accounts are logged in. ```javascript selectAccount(); ``` -------------------------------- ### Get Account by Username or Home ID Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/vanillajs-spa/README.md Retrieve active user accounts using `getAccountByUsername()` or `getAccountByHomeId()` if you know the user's identifier. ```javascript myMSALObj.getAccountByUsername(username); // or myMSALObj.getAccountByHomeId(homeId); ``` -------------------------------- ### Show Welcome Message Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Updates the UI to display a welcome message and user claims after successful authentication. Call this function with the authenticated account object. ```javascript const account = myMSALObj.getActiveAccount(); showWelcomeMessage(account); ``` -------------------------------- ### Sign in using Popup Flow with MSAL.js Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/vanillajs-spa/README.md Use the `loginPopup` API for interactive sign-in. Ensure you handle potential errors. ```javascript myMSALObj.loginPopup(loginRequest) .then((response) => { // your logic }) .catch(error => { console.error(error); }); ``` -------------------------------- ### GET /api/greeting Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md This endpoint provides a greeting message and is protected by Azure Easy Auth, requiring a valid JWT Bearer token with the 'Greeting.Read' scope. ```APIDOC ## GET /api/greeting ### Description Greeting endpoint in Azure Function protected by Easy Auth and scope validation. ### Method GET ### Endpoint /api/greeting ### Parameters #### Request Headers - **Authorization** (string) - Required - `Bearer {accessToken}` ### Request Example ```http GET /api/greeting HTTP/1.1 Host: myfunction.azurewebsites.net Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc... ``` ### Response #### Success Response (200) - **body** (string) - "Hello, world. You were able to access this because you provided a valid access token with the Greeting.Read scope as a claim." #### Error Response (403) - **body** (string) - "Invalid token." or "Missing required scope." ``` -------------------------------- ### Handle ServerError in MSAL.js Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/errors.md Catch and handle errors returned from the Azure AD server. This example demonstrates re-authenticating if the token is expired or logging a consent denial. ```javascript import { ServerError } from '@azure/msal-browser'; myMSALObj.acquireTokenSilent(request) .catch(error => { if (error instanceof ServerError) { if (error.code === 'invalid_grant') { console.log('Token expired, need to re-authenticate'); return myMSALObj.acquireTokenPopup(request); } if (error.code === 'access_denied') { console.log('User denied consent'); } } }); ``` -------------------------------- ### Configure CORS for Express Backend Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/configuration.md Set up Cross-Origin Resource Sharing (CORS) for an Express.js backend to allow requests from specified origins. Ensure the 'cors' package is installed. ```javascript const cors = require('cors'); app.use(cors({ origin: ['http://localhost:3000', 'https://myapp.com'], credentials: true })); ``` -------------------------------- ### Initialize Component and Subscribe to Auth Events Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/angular-spa.md Initializes the component by subscribing to MSAL interaction status and token acquisition events. Stores token expiration in localStorage. ```typescript ngOnInit() { // Subscribe to interaction completion this.msalBroadcastService.inProgress$ .pipe( filter((status) => status === InteractionStatus.None), takeUntil(this._destroying$) ) .subscribe(() => { this.setLoginDisplay(); }); // Capture token expiration this.msalBroadcastService.msalSubject$ .pipe(filter((msg) => msg.eventType === EventType.ACQUIRE_TOKEN_SUCCESS)) .subscribe(msg => { this.tokenExpiration = (msg.payload as any).expiresOn; localStorage.setItem('tokenExpiration', this.tokenExpiration); }); } ``` -------------------------------- ### showWelcomeMessage Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Updates the UI to display a welcome message and user claims after authentication. It manages the visibility of sign-in/sign-out buttons and welcome messages, and populates a table with token claims. ```APIDOC ## showWelcomeMessage ### Description Updates UI to show welcome message and user claims after authentication. ### Signature ```javascript function showWelcomeMessage(account: AccountInfo): void ``` ### Parameters #### Path Parameters - **account** (AccountInfo) - Required - Authenticated account object containing username and idTokenClaims ### Behavior 1. Hides sign-in button (adds 'd-none' class) 2. Shows sign-out button (removes 'd-none' class) 3. Hides title div (adds 'd-none' class) 4. Shows welcome div (removes 'd-none' class) 5. Sets welcome message: `"Welcome {username}!"` 6. Calls `updateTable()` with account to display token claims ### Example ```javascript const account = myMSALObj.getActiveAccount(); showWelcomeMessage(account); ``` ``` -------------------------------- ### Handle BrowserAuthError in MSAL.js Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/errors.md Catch and handle browser-specific authentication errors using a switch statement on the error code. This example shows handling popup and iframe redirection errors. ```javascript import { BrowserAuthError } from '@azure/msal-browser'; myMSALObj.loginRedirect() .catch(error => { if (error instanceof BrowserAuthError) { switch (error.code) { case 'popup_window_error': console.log('User must allow popups'); break; case 'redirect_in_iframe': console.log('Cannot use redirect in iframe'); break; } } }); ``` -------------------------------- ### Initiate User Login Redirect Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/angular-spa.md Initiates the user login process using the MSAL redirect flow. Uses configured scopes if available, otherwise requests default scopes. ```typescript login() { if (this.msalGuardConfig.authRequest) { this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest); } else { this.authService.loginRedirect(); } } ``` -------------------------------- ### GET /api/application Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md Retrieves application information from Microsoft Graph using the client credentials flow. This endpoint is designed for app-only access, meaning it authenticates the application itself rather than a user. ```APIDOC ## GET /api/application ### Description Returns application information from Microsoft Graph using client credentials flow (app-only access). ### Method GET ### Endpoint /api/application ### Parameters #### Request Body None ### Request Example ```http GET /api/application HTTP/1.1 Host: localhost:8080 ``` ### Response #### Success Response (200) - **id** (guid) - Object ID of the application - **appId** (guid) - Application (client) ID - **displayName** (string) - The application's display name - **identifierUris** (array) - Collection of URIs that identify an application - **replyUrlsWithType** (array) - Reply URLs defined for the application - **requiredResourceAccess** (array) - Specifies the resources that the application requires access to, and the set of permissions which it requires for each resource #### Response Example ```json { "id": "guid-object-id", "appId": "guid-app-id", "displayName": "My Application", "identifierUris": [ "https://myapp.example.com" ], "replyUrlsWithType": [ { "url": "http://localhost:3000", "type": "Web" } ], "requiredResourceAccess": [ { "resourceAppId": "00000003-0000-0000-c000-000000000000", "resourceAccess": [ { "id": "guid-scope-id", "type": "Scope" } ] } ] } ``` ### Error Handling - **500**: Token acquisition error or Graph API error. Returns 'Internal Server Error'. ``` -------------------------------- ### Access API with Authorization Header Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/protect-api/README.md Use curl to send a GET request to the API endpoint with a valid Bearer token in the Authorization header. This demonstrates how to authenticate requests to your protected API. ```console $ curl http://localhost:8080/ -H "Authorization: Bearer {VALID-ACCESS-TOKEN}" Hello, world. You were able to access this because you provided a valid access token with the Greeting.Read scope as a claim. ``` -------------------------------- ### Express JWT Middleware Setup Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/api-protection.md Express middleware for validating JWT access tokens. It fetches signing keys from Azure AD and verifies token claims like audience and issuer. ```javascript app.use(jwt({ secret: jwks.expressJwtSecret({ jwksUri: 'https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys' }), audience: config.auth.audience, issuer: 'https://login.microsoftonline.com/{tenant}/v2.0', algorithms: ['RS256'] })) ``` ```javascript app.use(jwt({ secret: jwks.expressJwtSecret({ jwksUri: 'https://login.microsoftonline.com/Enter_the_Tenant_ID/discovery/v2.0/keys' }), audience: 'Enter_the_Application_Id', issuer: 'https://login.microsoftonline.com/Enter_the_Tenant_ID/v2.0', algorithms: ['RS256'] })); // After middleware, req.auth contains decoded token app.get('/protected', (req, res) => { console.log('Subject:', req.auth.sub); console.log('Scopes:', req.auth.scp); res.send('Authenticated!'); }); ``` -------------------------------- ### Handle InteractionRequiredAuthError with Redirect in Vanilla JS Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/errors.md Acquire a token using redirect flow when silent acquisition fails due to InteractionRequiredAuthError. This example demonstrates the redirect approach for interactive token acquisition. ```javascript async function getTokenRedirect(request, account) { return await myMSALObj.acquireTokenSilent(request) .catch(async (error) => { if (error instanceof msal.InteractionRequiredAuthError) { console.log("Silent token acquisition failed"); console.log("Acquiring token using redirect"); myMSALObj.acquireTokenRedirect(request); } else { console.error(error); } }); } ``` -------------------------------- ### Token Request (Client Credentials) Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/configuration.md Use this request object with `acquireTokenByClientCredential()`. Scopes must be in the format `{resource}/.default`. ```javascript { scopes: string[], forceRefresh?: boolean } ``` -------------------------------- ### React App Configuration with Environment Variables Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/configuration.md Configure MSAL client ID, authority, and redirect URI using React app's environment variables. Ensure these variables are prefixed with REACT_APP_. ```javascript const msalConfig = { auth: { clientId: process.env.REACT_APP_CLIENT_ID, authority: process.env.REACT_APP_AUTHORITY, redirectUri: process.env.REACT_APP_REDIRECT_URI } }; ``` -------------------------------- ### Protected Greeting Endpoint Implementation Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md This Express.js code snippet defines a GET endpoint that requires a JWT access token with the 'Greeting.Read' scope for authorization. It uses middleware for JWT validation and scope checking. ```javascript app.get('/', jwtAuthz(['Greeting.Read'], { customScopeKey: 'scp', customUserKey: 'auth' }), (req, res) => { res.send('Hello, world. You were able to access this because you provided ' + 'a valid access token with the Greeting.Read scope as a claim.'); } ); ``` -------------------------------- ### Rebase and Force Push for PR Updates Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/CONTRIBUTING.md Use these commands to update your fork and refresh your pull request after making changes based on feedback. ```shell git rebase master -i git push -f ``` -------------------------------- ### API Protection and Authorization Reference Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/INDEX.md Explains how to protect APIs using Express and Azure Functions with JWT validation. It details middleware for token validation and scope-based authorization, along with examples of protected endpoints and error handling. ```APIDOC ## API Protection and Authorization Reference ### Description Express and Azure Functions protecting APIs with JWT validation. ### API Surface - `jwt()` middleware: Validates JWT access tokens - `jwtAuthz()` middleware: Enforces scope-based authorization - Protected Greeting Endpoint (Express.js) - Protected Greeting Function (Azure Functions) - Error responses and status codes - Scope validation configuration ``` -------------------------------- ### signIn Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md Initiates user login via popup or redirect based on browser compatibility. This function handles the MSAL login process and subsequent response handling. ```APIDOC ## signIn ### Description Initiates user login via popup or redirect based on browser compatibility. ### Signature ```javascript async function signIn(method: "popup" | "redirect"): Promise ``` ### Parameters #### Query Parameters - **method** ("popup" | "redirect") - Required - Login method: "popup" for popup window or "redirect" for full-page redirect ### Returns `Promise` - Resolves when login completes ### Behavior 1. Sets global `signInType` variable (IE forces redirect regardless of method) 2. If method is "popup": - Calls `myMSALObj.loginPopup()` with login scopes - Overrides `redirectUri` to "/redirect" - Calls `handleResponse()` on success - Logs error on failure 3. If method is "redirect": - Calls `myMSALObj.loginRedirect()` with login scopes - User is redirected to Azure AD login page ### Throws Rejects with error if: - User cancels login in popup - Network error occurs - Invalid configuration ### Example ```javascript // Start login with popup await signIn("popup"); // Or start login with redirect await signIn("redirect"); ``` ``` -------------------------------- ### Access Azure Function API with Curl Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/protect-function-app/README.md Use this curl command to make a GET request to the Azure Function API. Ensure you replace placeholders with your function name and a valid access token. The Authorization header is required for authentication. ```console $ curl https://.azurewebsites.net/api/greeting -H "Authorization: Bearer " ``` -------------------------------- ### Express.js Endpoint for Client Credentials Flow Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/endpoints.md This JavaScript code implements the GET /api/application route. It acquires a token using client credentials and then calls the Microsoft Graph API to fetch application information. Ensure MSAL Node and HTTPS modules are imported. ```javascript app.get('/api/application', (req, res) => { const tokenRequest = { scopes: ['https://graph.microsoft.com/.default'] }; msalConfidentialClientApp.acquireTokenByClientCredential(tokenRequest) .then((response) => { console.log(`Token from cache: ${response.fromCache}`); const options = { headers: { Authorization: `Bearer ${response.accessToken}` } }; https.get('https://graph.microsoft.com/v1.0/applications/' + msalConfig.auth.clientObjectId, options, (graphResponse) => { let graphData = ''; graphResponse.on('data', chunk => { graphData += chunk; }); graphResponse.on('end', () => { res.send(graphData); }); }).end(); }) .catch((error) => { console.error('Token acquisition failed:', error); res.status(500).send('Authentication failed'); }); }); ``` -------------------------------- ### Publish Azure Function App Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/protect-function-app/README.md Use this command to deploy your Azure Function App to the cloud. Replace `` with the actual name of your Function App. ```bash func azure functionapp publish ``` -------------------------------- ### ConfidentialClientApplication Configuration (Client Credentials) Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/configuration.md Use this configuration for server-side applications that need to call APIs as the application itself. Ensure all required properties are provided. ```javascript { auth: { clientId: string, clientSecret: string, authority: string, clientObjectId?: string } } ``` -------------------------------- ### Acquire Access Token with Redirect Fallback Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/api-reference/vanillajs-spa.md This snippet shows how to define a token request and use the getTokenRedirect function to obtain an access token. It includes a check for the token and demonstrates how to use it in an API call by setting the Authorization header. ```javascript const tokenRequest = { scopes: ["https://graph.microsoft.com/user.read"] }; const token = await getTokenRedirect(tokenRequest); if (token) { // Use token in API call const headers = new Headers(); headers.append("Authorization", `Bearer ${token.accessToken}`); } ``` -------------------------------- ### MSAL Node Applications API Reference Source: https://github.com/azure-samples/ms-identity-docs-code-javascript/blob/main/_autodocs/INDEX.md Details server-side Node.js authentication using MSAL Node, covering Client Credentials Flow and On-Behalf-Of Flow. It includes functions for acquiring tokens and discusses caching behavior, token refresh patterns, and Express.js setup. ```APIDOC ## MSAL Node Applications API Reference ### Description Server-side Node.js authentication using MSAL Node. ### API Surface - Client Credentials Flow configuration (app-to-app authentication) - On-Behalf-Of Flow configuration (API-to-API with user delegation) - `acquireTokenByClientCredential()`: Acquires token using client credentials - `acquireTokenOnBehalfOf()`: Acquires token for downstream API on behalf of user - Caching behavior and token refresh patterns - Express.js setup examples ```