Quickstart: Sign in users in a single-page app (SPA) and call the Microsoft Graph API
Artikkeli
In this quickstart, you use a sample single-page app (SPA) to show you how to sign in users by using the authorization code flow with Proof Key for Code Exchange (PKCE) and call the Microsoft Graph API. The sample uses the Microsoft Authentication Library to handle authentication.
To complete registration, provide the application a name, specify the supported account types, and add a redirect URI. Once registered, the application Overview pane displays the identifiers needed in the application source code.
If you have access to multiple tenants, use the Settings icon
in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
Browse to Identity > Applications > App registrations, select New registration.
Enter a Name for the application, such as identity-client-spa.
For Supported account types, select Accounts in this organizational directory only. For information on different account types, select the Help me choose option.
Select Register.
The application's Overview pane is displayed when registration is complete. Record the Directory (tenant) ID and the Application (client) ID to be used in your application source code.
In your IDE, open the project folder, ms-identity-docs-code-javascript, containing the sample.
Open vanillajs-spa/App/public/authConfig.js and update the following values with the information recorded in the admin center.
/**
* Configuration object to be passed to MSAL instance on creation.
* For a full list of MSAL.js configuration parameters, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
*/
const msalConfig = {
auth: {
// WORKFORCE TENANT
authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Replace the placeholder with your tenant info
// EXTERNAL TENANT
// authority: "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/", // Replace the placeholder with your tenant subdomain
redirectUri: '/', // You must register this URI on App Registration. Defaults to window.location.href e.g. http://localhost:3000/
navigateToLoginRequestUrl: true, // If "true", will navigate back to the original request location before processing the auth code response.
},
cache: {
cacheLocation: 'sessionStorage', // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO.
storeAuthStateInCookie: false, // set this to true if you have to support IE
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case msal.LogLevel.Error:
console.error(message);
return;
case msal.LogLevel.Info:
console.info(message);
return;
case msal.LogLevel.Verbose:
console.debug(message);
return;
case msal.LogLevel.Warning:
console.warn(message);
return;
}
},
},
},
};
/**
* Scopes you add here will be prompted for user consent during sign-in.
* By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
* For more information about OIDC scopes, visit:
* https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
* https://learn.microsoft.com/en-us/entra/identity-platform/permissions-consent-overview#openid-connect-scopes
*/
const loginRequest = {
scopes: ["User.Read"],
};
/**
* An optional silentRequest object can be used to achieve silent SSO
* between applications by providing a "login_hint" property.
*/
// const silentRequest = {
// scopes: ["openid", "profile"],
// loginHint: "example@domain.net"
// };
// exporting config object for jest
if (typeof exports !== 'undefined') {
module.exports = {
msalConfig: msalConfig,
loginRequest: loginRequest,
};
module.exports = {
msalConfig: msalConfig,
loginRequest: loginRequest,
};
}
clientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.
authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
redirectUri - The Redirect URI of the application. If necessary, replace the text in quotes with the redirect URI that was recorded earlier.
In your IDE, open the project folder, ms-identity-docs-code-javascript/react-spa, containing the sample.
Open react-spa/src/authConfig.js and update the following values with the information recorded in the admin center.
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { LogLevel } from "@azure/msal-browser";
/**
* Configuration object to be passed to MSAL instance on creation.
* For a full list of MSAL.js configuration parameters, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
*/
export const msalConfig = {
auth: {
clientId: "Enter_the_Application_Id_Here",
authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
redirectUri: "http://localhost:3000",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level, message, containsPii) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
default:
return;
}
}
}
}
};
/**
* Scopes you add here will be prompted for user consent during sign-in.
* By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
* For more information about OIDC scopes, visit:
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
*/
export const loginRequest = {
scopes: ["User.Read"]
};
/**
* Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
*/
export const graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
};
clientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.
authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
redirectUri - The Redirect URI of the application. If necessary, replace the text in quotes with the redirect URI that was recorded earlier.
In your IDE, open the project folder, ms-identity-docs-code-javascript/angular-spa, containing the sample.
Open angular-spa/src/app/app.module.ts and update the following values with the information recorded in the admin center.
// Required for Angular multi-browser support
import { BrowserModule } from '@angular/platform-browser';
// Required for Angular
import { NgModule } from '@angular/core';
// Required modules and components for this application
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProfileComponent } from './profile/profile.component';
import { HomeComponent } from './home/home.component';
// HTTP modules required by MSAL
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
// Required for MSAL
import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser';
import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular';
const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1;
export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication({
auth: {
// 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID
clientId: "Enter_the_Application_Id_Here",
// Full directory URL, in the form of https://login.microsoftonline.com/<tenant>
authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
// Must be the same redirectUri as what was provided in your app registration.
redirectUri: "http://localhost:4200",
},
cache: {
cacheLocation: BrowserCacheLocation.LocalStorage,
storeAuthStateInCookie: isIE
}
});
}
// MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph)
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
return {
interactionType: InteractionType.Redirect,
protectedResourceMap
};
}
// MSAL Guard is required to protect routes and require authentication before accessing protected routes
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
authRequest: {
scopes: ['user.read']
}
};
}
// Create an NgModule that contains the routes and MSAL configurations
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ProfileComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
MsalModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: MSAL_INSTANCE,
useFactory: MSALInstanceFactory
},
{
provide: MSAL_GUARD_CONFIG,
useFactory: MSALGuardConfigFactory
},
{
provide: MSAL_INTERCEPTOR_CONFIG,
useFactory: MSALInterceptorConfigFactory
},
MsalService,
MsalGuard,
MsalBroadcastService
],
bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule { }
clientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.
authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
redirectUri - The Redirect URI of the application. If necessary, replace the text in quotes with the redirect URI that was recorded earlier.
In your IDE, open the project folder, ms-identity-docs-code-dotnet/spa-blazor-wasm, containing the sample.
Open spa-blazor-wasm/wwwroot/appsettings.json and update the following values with the information recorded earlier in the admin center.
{
"AzureAd": {
"Authority": "https://login.microsoftonline.com/<Enter the tenant ID obtained from the Microsoft Entra admin center>",
"ClientId": "Enter the client ID obtained from the Microsoft Entra admin center",
"ValidateAuthority": true
}
}
Authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
ClientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.
Run the project with a web server by using Node.js:
To start the server, run the following commands from within the project directory:
cd vanillajs-spa/App
npm install
npm start
Copy the https URL that appears in the terminal, for example, https://localhost:3000, and paste it into a browser. We recommend using a private or incognito browser session.
Follow the steps and enter the necessary details to sign in with your Microsoft account. You'll be requested an email address so a one time passcode can be sent to you. Enter the code when prompted.
The application will request permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select Accept. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
Run the project with a web server by using Node.js:
To start the server, run the following commands from within the project directory:
cd react-spa/App
npm install
npm start
Copy the https URL that appears in the terminal, for example, https://localhost:3000, and paste it into a browser. We recommend using a private or incognito browser session.
Follow the steps and enter the necessary details to sign in with your Microsoft account. You're requested an email address so a one time passcode can be sent to you. Enter the code when prompted.
The application requests permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select Accept. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
Run the project with a web server by using Node.js:
To start the server, run the following commands from within the project directory:
cd angular-spa/App
npm install
npm start
Copy the https URL that appears in the terminal, for example, https://localhost:4200, and paste it into a browser address bar. We recommend using a private or incognito browser session.
Follow the steps and enter the necessary details to sign in with your Microsoft account. You'll be requested an email address so a one time passcode can be sent to you. Enter the code when prompted.
The application will request permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select Accept. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
Run the project with a web server by using dotnet:
To start the server, run the following commands from within the project directory:
cd spa-blazor-wasm
dotnet workload install wasm-tools
dotnet run
Copy the http URL that appears in the terminal, for example, http://localhost:5000, and paste it into a browser. We recommend using a private or incognito browser session.
Follow the steps and enter the necessary details to sign in with your Microsoft account. You'll be requested an email address so a one time passcode can be sent to you. Enter the code when prompted.
The application will request permission to maintain access to data you have given it access to, and to sign you in and read your profile. Select Accept. The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
To enable your application to sign in users with Microsoft Entra, Microsoft Entra External ID must be made aware of the application you create. The app registration establishes a trust relationship between the app and Microsoft Entra. When you register an application, External ID generates a unique identifier known as an Application (client) ID, a value used to identify your app when creating authentication requests.
The following steps show you how to register your app in the Microsoft Entra admin center:
If you have access to multiple tenants, use the Settings icon
in the top menu to switch to your external tenant from the Directories + subscriptions menu.
Browse to Identity >Applications > App registrations.
Select + New registration.
In the Register an application page that appears;
Enter a meaningful application Name that is displayed to users of the app, for example ciam-client-app.
Under Supported account types, select Accounts in this organizational directory only.
Select Register.
The application's Overview pane displays upon successful registration. Record the Application (client) ID to be used in your application source code.
To specify your app type to your app registration, follow these steps:
Under Manage, select Authentication.
On the Platform configurations page, select Add a platform, and then select SPA option.
For the Redirect URIs enter http://localhost:3000.
Select Configure to save your changes.
To specify your app type to your app registration, follow these steps:
Under Manage, select Authentication.
On the Platform configurations page, select Add a platform, and then select SPA option.
For the Redirect URIs enter http://localhost:3000.
Select Configure to save your changes.
To specify your app type to your app registration, follow these steps:
Under Manage, select Authentication.
On the Platform configurations page, select Add a platform, and then select SPA option.
For the Redirect URIs enter http://localhost:4200.
Select Configure to save your changes.
Grant admin consent
Once you register your application, it gets assigned the User.Read permission. However, since the tenant is an external tenant, the customer users themselves can't consent to this permission. You as the tenant administrator must consent to this permission on behalf of all the users in the tenant:
From the App registrations page, select the application that you created (such as ciam-client-app) to open its Overview page.
Under Manage, select API permissions.
Select Grant admin consent for <your tenant name>, then select Yes.
Select Refresh, then verify that Granted for <your tenant name> appears under Status for the permission.
Create a user flow
For the customer users to see the sign-up or sign-in experience when they use your app, you need to associate your app with a user flow. Although many applications can be associated with your user flow, a single application can only be associated with one user flow.
On the sidebar menu, select Identity.
Select External Identities, then User flows.
In the User flows page, select the User flow name you created earlier, for example, SignInSignUpSample.
Under Use, select Applications.
Select Add application.
Select the application from the list such as ciam-client-app or use the search box to find the application, and then select it.
Choose Select.
Once you associate your app with a user flow, you can test your user flow by simulating a user’s sign-up or sign-in experience with your application from within the Microsoft Entra admin center. To do so, use the steps in Test your sign-up and sign-in user flow.
Associate the SPA with the user flow
For the customer users to see the sign-up or sign-in experience when they use your app, you need to associate your app with a user flow. Although many applications can be associated with your user flow, a single application can only be associated with one user flow.
On the sidebar menu, select Identity.
Select External Identities, then User flows.
In the User flows page, select the User flow name you created earlier, for example, SignInSignUpSample.
Under Use, select Applications.
Select Add application.
Select the application from the list such as ciam-client-app or use the search box to find the application, and then select it.
Choose Select.
Once you associate your app with a user flow, you can test your user flow by simulating a user’s sign-up or sign-in experience with your application from within the Microsoft Entra admin center. To do so, use the steps in Test your sign-up and sign-in user flow.
Clone or download sample SPA
To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.
Open App/public/authConfig.js and replace the following with the values obtained from the Microsoft Entra admin center:
Enter_the_Application_Id_Here and replace it with the Application (client) ID of the app you registered earlier.
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.
Save the file.
Open SPA\src\authConfig.js and replace the following with the values obtained from the Microsoft Entra admin center:
Enter_the_Application_Id_Here and replace it with the Application (client) ID of the app you registered earlier.
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.
Save the file.
Open SPA/src/app/auth-config.ts and replace the following with the values obtained from the Microsoft Entra admin center:
Enter_the_Application_Id_Here and replace it with the Application (client) ID of the app you registered earlier.
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.
To start the server, run the following commands from within the project directory:
cd 1-Authentication\0-sign-in-vanillajs\App
npm install
npm start
Copy the https URL that appears in the terminal, for example, https://localhost:3000, and paste it into a browser. We recommend using a private or incognito browser session.
Sign-in with an account registered to the tenant.
The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
To start the server, run the following commands from within the project directory:
cd 1-Authentication\1-sign-in-react\SPA
npm install
npm start
Copy the https URL that appears in the terminal, for example, https://localhost:3000, and paste it into a browser. We recommend using a private or incognito browser session.
Sign-in with an account registered to the external tenant.
The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
To start the server, run the following commands from within the project directory:
cd 1-Authentication\2-sign-in-angular\SPA
npm install
npm start
Copy the https URL that appears in the terminal, for example, https://localhost:4200, and paste it into a browser. We recommend using a private or incognito browser session.
Sign-in with an account registered to the external tenant.
The following screenshot appears, indicating that you have signed in to the application and have accessed your profile details from the Microsoft Graph API.
Sign out from the application
Find the Sign out button on the page, and select it.
You'll be prompted to pick an account to sign out from. Select the account you used to sign in.
A message appears indicating that you have signed out. You can now close the browser window.