page_type | description | languages | products | urlFragment | extensions | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
This sample demonstrates an Angular single-page application (SPA) which lets a user authenticate with their Azure AD tenant and obtains an access token to call an ASP.NET Core web API, protected by Azure Active Directory (Azure AD). |
|
|
spa-msal-angular-graph-obo |
|
An Angular single-page application calling an AspNetCore web API which calls the Microsoft Graph API using the on-behalf-of(OBO) flow
- Overview
- Scenario
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Contributing
- Learn More
This sample demonstrates an Angular single-page application (SPA) which lets a user authenticate with their Azure AD tenant and obtains an access token to call an ASP.NET Core web API, protected by Azure Active Directory (Azure AD). The web API then proceeds to obtain another access token for Microsoft Graph API using the OAuth 2.0 on-behalf-of flow. The web API's call to Microsoft Graph is made using the Microsoft Graph SDK.
- The sample implements an onboarding scenario where a profile is created for a new user whose fields are pre-populated by the available information about the user on Microsoft Graph.
- The ProfileSPA uses MSAL Angular to authenticate a user.
- Once the user authenticates, ProfileSPA obtains an access token from Azure AD.
- The access token is then used to authorize the ProfileAPI. This access token is also used to obtain another access token to call MS Graph API on user's behalf. In order to call MS Graph API, ProfileAPI uses the Microsoft Graph SDK.
- To protect its endpoint and accept only the authorized calls, the ProfileAPI uses Microsoft.Identity.Web.
File/folder | Description |
---|---|
SPA/src/app/auth-config.ts |
Authentication parameters for SPA project reside here. |
SPA/src/app/app.module.ts |
MSAL Angular is initialized here. |
API/ProfileAPI/appsettings.json |
Authentication parameters for API project reside here. |
API/ProfileAPI/Startup.cs |
Microsoft.Identity.Web is initialized here. |
API/ProfileAPI/ProfileController.cs |
MVC controller serving API endpoints |
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- An Azure AD tenant. For more information, see: How to get an Azure AD tenant
- A user account in your Azure AD tenant.
This sample will not work with a personal Microsoft account. If you're signed in to the Azure portal with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.git
or download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
cd ms-identity-javascript-angular-tutorial
cd 6-AdvancedScenarios/1-call-api-obo/API/ProfileAPI
dotnet restore
dotnet dev-certs https --clean
dotnet dev-certs https --trust
For more information and potential issues, see: HTTPS in .NET Core.
cd ../../
cd SPA
npm install
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
> :warning: If you have never used **Microsoft Graph PowerShell** before, we recommend you go through the [App Creation Scripts Guide](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step.
1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory
1. In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
1. Run the script to create your Azure AD application and configure the code of the sample application accordingly.
1. For interactive process -in PowerShell, run:
cd .\AppCreationScripts\
.\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"
> Other ways of running the scripts are described in [App Creation Scripts guide](./AppCreationScripts/AppCreationScripts.md). The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
To manually register the apps, as a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD tenant.
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
ProfileAPI
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where you can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret
). - Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
💡 For enhanced security, instead of using client secrets, consider using certificates and Azure KeyVault.
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- Since this app signs-in users, we will now proceed to select delegated permissions, which is requested by apps that signs-in users.
- In the Delegated permissions section, select User.Read, offline_access in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Type a key description (for instance
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can publish the permission as an API for which client applications can obtain access tokens for. The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this API. To declare an resource URI(Application ID URI), follow the following steps:
- Select Set next to the Application ID URI to generate a URI that is unique for this app.
- For this sample, accept the proposed Application ID URI (
api://{clientId}
) by selecting Save. Read more about Application ID URI at Validation differences by supported account types (signInAudience).
- All APIs must publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:
- Select Add a scope button open the Add a scope screen and enter the values as indicated below:
- For Scope name, use
access_graph_on_behalf_of_user
. - Select Admins and users options for Who can consent?.
- For Admin consent display name type in Access Microsoft Graph as the signed-in user.
- For Admin consent description type in Allow the app to access Microsoft Graph Api as the signed-in user.
- For User consent display name type in Access Microsoft Graph on your behalf.
- For User consent description type in Allow the Microsoft Graph APi on your behalf..
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select the Manifest blade on the left.
- Set
accessTokenAcceptedVersion
property to 2. - Select on Save.
- Set
-
Still on the same app registration, select the Token configuration blade to the left.
-
Select Add optional claim:
- Select optional claim type, then choose Access.
- Select the optional claim idtyp.
Indicates token type. This claim is the most accurate way for an API to determine if a token is an app token or an app+user token. This is not issued in tokens issued to users.
- Select Add to save your changes.
- Select optional claim type, then choose Access.
-
Still on the same app registration, select the Manifest blade to the left.
- Set the optionalClaims property as shown below to request client capabilities claim xms_cc:
"optionalClaims": { "accessToken": [ { "additionalProperties": [], "essential": false, "name": "xms_cc", "source": null } ], "idToken": [], "saml2Token": [] }
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
API\ProfileAPI\appsettings.json
file. - Find the key
Enter the client Secret
and replace the existing value with the generated secret that you saved during the creation ofProfileAPI
copied from the Azure portal. - Find the key
Enter the client ID (aka 'Application ID')
and replace the existing value with the application ID (clientId) ofProfileAPI
app copied from the Azure portal. - Find the key
Enter the tenant ID
and replace the existing value with your Azure AD tenant/directory ID.
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
ProfileSPA
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Single-page application option.
- In the Redirect URI section enter the following redirect URIs:
http://localhost:4200
http://localhost:4200/auth
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URIs:
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
- Select the Add a permission button and then:
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
ProfileAPI
.- Since this app signs-in users, we will now proceed to select delegated permissions, which is requested by apps that signs-in users.
- In the Delegated permissions section, select access_graph_on_behalf_of_user in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose Access.
- Select the optional claim acct.
Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.
- Select Add to save your changes.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
SPA\src\app\auth-config.ts
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofProfileSPA
app copied from the Azure portal. - Find the key
Enter_the_Tenant_Info_Here
and replace the existing value with your Azure AD tenant/directory ID. - Find the key
Enter_the_Web_Api_Application_Id_Here
and replace the existing value with the application ID (clientId) ofProfileAPI
app copied from the Azure portal.
For a middle-tier web API (ProfileAPI
) to be able to call a downstream web API, the middle tier app needs to be granted the required permissions as well. However, since the middle-tier cannot interact with the signed-in user, it needs to be explicitly bound to the client app in its Azure AD registration. This binding merges the permissions required by both the client and the middle-tier web API and presents it to the end user in a single consent dialog. The user then consent to this combined set of permissions. To achieve this, you need to add the Application Id of the client app to the knownClientApplications
property in the manifest of the web API. Here's how:
- In the Azure portal, navigate to your
ProfileAPI
app registration, and select the Manifest blade. - In the manifest editor, change the
knownClientApplications: []
line so that the array contains the Client ID of the client application (ProfileSPA
) as an element of the array.
For instance:
"knownClientApplications": ["ca8dca8d-f828-4f08-82f5-325e1a1c6428"],
- Save the changes to the manifest.
Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:
cd SPA
npm start
In a separate console window, execute the following commands:
cd API/ProfileAPI
dotnet run
- Open your browser and navigate to
http://localhost:4200
. - Sign-in using the button on top-right corner.
- If this is your first sign-in, you will be redirected to the onboarding page (the app will try to make a GET request: if this is the first time, it will fail -this is expected).
- Hit Accept and a new account will be created for you in the database, pre-populated by the information about you fetched from Microsoft Graph.
- Submit your changes. When you sign-in next time, the application will recognize you and show you the profile associated with your ID in the database.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
Expand for troubleshooting info
Use Stack Overflow 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
dotnet
ms-identity
adal
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
To debug the .NET Core web API that comes with this sample, install the C# extension for Visual Studio Code.
Learn more about using .NET Core with Visual Studio Code.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
In Startup.cs, add services for authentication, token validation, token caching and Graph SDK support using the Microsoft.Identity.Web APIs as shown below:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamAPI"))
.AddInMemoryTokenCaches();
services.AddDbContext<ProfileContext>(opt => opt.UseInMemoryDatabase("Profile"));
services.AddControllers();
// Allowing CORS for all domains and methods for the purpose of sample
services.AddCors(o => o.AddPolicy("default", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("WWW-Authenticate");
}));
}
Notice the WWW-Authenticate header exposed in the CORS policy setup. This header tells the client app that authentication is needed for the middle-tier API, as middle-tier API has no user interface and cannot prompt the user itself.
The middle-tier application adds the client to the knownClientApplications
list in its manifest, and then the client app can trigger a combined consent flow for both itself and the middle-tier application. On the Microsoft identity platform, this is done using the /.default
scope. When triggering a consent screen using known client applications and /.default
, the consent screen will show permissions for both the client to the middle-tier API, and also request whatever permissions are required by the middle-tier API. The user provides consent for both applications, and then the OBO flow works.
ℹ️ KnownClientApplications is an attribute in application manifest. It is used for bundling consent if you have a solution that contains two (or more) parts: a client app and a custom web API. If you enter the
appID
(clientID) of the client app into this array, the user will have to consent only once to the client app. Azure AD will know that consenting to the client means implicitly consenting to the web API. It will automatically provision service principals for both the client and web API at the same time. Both the client and the web API app must be registered in the same tenant.
Continuous access evaluation (CAE) enables applications to do just-in time token validation, for instance enforcing user session revocation in the case of password change/reset but there are other benefits. For details, see Continuous access evaluation.
Microsoft Graph is now CAE-enabled. This means that it can ask its client apps for more claims when conditional access policies require it. Your can enable your application to be ready to consume CAE-enabled APIs by:
- Declaring that the client app is capable of handling claims challenges.
- Processing the claim challenge when they are thrown by MS Graph Api.
The sample SPA (ProfileSPA) declares that it's CAE-capable by adding the clientCapabilities
property in the configuration in auth-config.ts:
export const msalConfig: Configuration = {
auth: {
clientId: 'Enter_the_Application_Id_Here',
authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here',
redirectUri: '/auth',
postLogoutRedirectUri: '/',
clientCapabilities: ['CP1'] // This lets the resource server know that this client can handle claim challenges.
},
}
The middle-tier web API (ProfileAPI) also needs to declare that it's CAE-capable in appsettings.json:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "Enter the tenant ID",
"ClientId": "Enter the client ID (aka 'Application ID')",
"ClientSecret": "Enter the client Secret",
"ClientCapabilities": [ "CP1" ]
},
Once the middle-tier web API (ProfileAPI) app receives the CAE claims challenge from Microsoft Graph, it needs to process the challenge and redirect the user back to Azure AD for re-authorization. However, since the middle-tier web API does not have UI to carry out this, it needs to propagate the error to the client app (ProfileSPA) instead, where it can be handled. This is shown in ProfileController:
try
{
User profile = await _graphServiceClient.Me.Request().GetAsync();
}
catch (ServiceException svcex) when (svcex.Message.Contains("Continuous access evaluation resulted in claims challenge"))
{
if (IsClientCapableofClaimsChallenge(HttpContext))
{
// append the WWW-Authenticate header from the Microsoft Graph response to the response to the client app
// to learn more, visit: https://learn.microsoft.com/azure/active-directory/develop/app-resilience-continuous-access-evaluation?tabs=dotnet
HttpContext.Response.Headers.Add("WWW-Authenticate", svcex.ResponseHeaders.WwwAuthenticate.ToString());
return Unauthorized(svcex.RawResponseBody);
}
else
{
return Unauthorized("Continuous access evaluation resulted in claims challenge but the client is not capable");
}
}
On the client side, we use MSAL's acquireToken
API and provide the claims challenge as a parameter in the token request. This is shown in profile.service.ts, where we handle the response from the Microsoft Graph API with the handleClaimsChallenge
method:
handleClaimsChallenge(response: HttpErrorResponse): void {
const authenticateHeader: string | null = response.headers.get('WWW-Authenticate');
const claimsChallengeMap = parseChallenges(authenticateHeader!);
let account: AccountInfo = this.authService.instance.getActiveAccount()!;
/**
* This method stores the claim challenge to the session storage in the browser to be used when acquiring a token.
* To ensure that we are fetching the correct claim from the storage, we are using the clientId
* of the application and oid (user’s object id) as the key identifier of the claim with schema
* cc.<clientId>.<oid><resource.hostname>
*/
addClaimsToStorage(
`cc.${msalConfig.auth.clientId}.${account?.idTokenClaims?.oid}.${new URL(protectedResources.profileApi.endpoint).hostname}`,
claimsChallengeMap['claims']
);
// make a token request afterwards
this.authService.instance.acquireTokenPopup({
account: account,
scopes: protectedResources.profileApi.scopes,
claims: claimsChallengeMap['claims']
}).catch((error) => {
console.log(error);
});
}
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- Azure AD code samples
- Overview of Microsoft Authentication Library (MSAL)
- Register an application with the Microsoft identity platform
- Configure a client application to access web APIs
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Application and service principal objects in Azure Active Directory
- Authentication Scenarios for Azure AD
- Building Zero Trust ready apps
- National Clouds
- Microsoft.Identity.Web
- Validating Access Tokens
- User and application tokens
- Validation differences by supported account types
- How to manually validate a JWT access token using the Microsoft identity platform