page_type | name | description | languages | products | urlFragment | extensions | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
React SPA with ASP.NET Core backend calling Microsoft Graph using the backend for frontend proxy architecture |
A React single-page application with an ASP.NET Core backend authenticating users and calling the Microsoft Graph API using the backend for frontend proxy architecture |
|
|
active-directory-aspnetcore-webapp-openidconnect-v2 |
|
React SPA with ASP.NET Core backend calling Microsoft Graph using the backend for frontend (BFF) proxy architecture
- Overview
- Scenario
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Next Steps
- Contributing
- Learn More
This sample demonstrates a React single-page application (SPA) with an ASP.NET Core backend that authenticates users and calls the Microsoft Graph API using the backend for frontend (BFF) proxy architecture. In this architecture, access tokens are retrieved and stored within the secure backend context, and the client side JavaScript application, which is served by the ASP.NET web app, is only indirectly involved in the authN/authZ process by routing the token and API requests to the backend. The trust between the frontend and backend is established via a secure cookie upon successful sign-in.
ℹ️ To learn how applications integrate with Microsoft Graph, consider going through the recorded session: An introduction to Microsoft Graph for developers
- The client-side React SPA initiates token acquisition by calling the login endpoint of the ASP.NET core web app.
- ASP.NET Core web app uses Microsoft.Identity.Web to sign-in a user and obtain a JWT ID Token and an Access Token from Microsoft Entra ID.
- ASP.NET Core web app uses the access token as a bearer token to authorize the user to call the Microsoft Graph API protected by Microsoft Entra ID.
- ASP.NET Core web app returns the Microsoft Graph
/me
endpoint response back to the React SPA.
sequenceDiagram
participant Frontend
participant Backend
participant Microsoft Entra ID
participant Graph
Frontend-)+Backend: /login
Backend-)+Microsoft Entra ID: login.microsoftonline.com
Microsoft Entra ID--)-Backend: token response
Backend--)-Frontend: /login response (auth state)
Frontend-)+Backend: /profile
Backend-)+Graph: graph.microsoft.com/v1.0/me
Graph--)-Backend: /me endpoint response
Backend--)-Frontend: /profile response (/me data)
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- An Microsoft Entra ID tenant. For more information, see: How to get a Microsoft Entra tenant
- A user account in your Microsoft Entra ID tenant.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2.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 2-WebApp-graph-user/2-6-BFF-Proxy
dotnet dev-certs https --clean
dotnet dev-certs https --trust
For more information and potential issues, see: HTTPS in .NET Core.
There is one project in this sample. To register it, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra 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. Ensure that you have PowerShell 7 or later.
1. Set the execution policy if this is the first time you are running external scripts:
```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
```
1. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.
1. For interactive process -in PowerShell, run:
```PowerShell
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.
> :information_source: This sample can make use of client certificates. You can use **AppCreationScripts** to register a Microsoft Entra application with certificates. See: [How to use certificates instead of client secrets](./README-use-certificate.md)
To manually register the apps, as a first step you'll need to:
- Sign in to the Microsoft Entra admin center.
- If your account is present in more than one Microsoft Entra 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 Microsoft Entra tenant.
- Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID 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
CallGraphBFF
. - 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 Web option.
- In the Redirect URI section enter the following redirect URI:
https://localhost:7000/api/auth/signin-oidc
https://localhost:7000/api/auth/signout-oidc
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URI:
- 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 Microsoft Entra admin center before navigating to any other screen or blade.
⚠️ For enhanced security, consider using certificates instead of client secrets. See: How to use certificates instead of secrets. - Type a key description (for instance
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- 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
- In the Delegated permissions section, select User.Read 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 ID.
- 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
2-6-BFF-Proxy/appsettings.json
file. - Find the string
Enter_the_Tenant_Id_Here
and replace it with your Microsoft Entra tenant/directory ID. - Find the string
Enter_the_Application_Id_Here
and replace it with the application ID (clientId) ofCallGraphBFF
app copied from the Microsoft Entra admin center. - Find the string
Enter_the_Client_Secret_Here
and replace it with the generated secret that you saved during the creation ofCallGraphBFF
copied from the Microsoft Entra admin center.
From your shell or command line, execute the following commands:
cd 2-WebApp-graph-user/2-6-BFF-Proxy/
dotnet run
- Open your browser and navigate to
https://localhost:7000
. - Select the Login button on the navigation bar to sign-in.
- Select the Profile button on the navigation bar to call Microsoft Graph.
ℹ️ 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. 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 [
microsoft-identity-web
ms-identity
adal
msal-net
msal
].
To provide feedback on or suggest features for Microsoft Entra ID, visit User Voice page.
In Program.cs, Microsoft Identity Web service is configured to obtain tokens to call downstream web APIs (here, Microsoft Graph):
// Add Microsoft.Identity.Web services to the container.
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(builder.Configuration.GetSection("DownstreamApi:Scopes").Value.Split(' '))
.AddMicrosoftGraph(builder.Configuration.GetValue<string>("DownstreamApi:BaseUrl"), builder.Configuration.GetValue<string>("DownstreamApi:Scopes"))
.AddInMemoryTokenCaches();
On the frontend side, the React SPA uses the AuthProvider HOC, which makes a GET call to the /api/auth/login
endpoint of the ASP.NET Core web app.
login = (postLoginRedirectUri) => {
let url = "api/auth/login";
const searchParams = new URLSearchParams({});
if (postLoginRedirectUri) {
searchParams.append('postLoginRedirectUri', encodeURIComponent(postLoginRedirectUri));
}
url = `${url}?${searchParams.toString()}`;
window.location.replace(url);
}
The controller in AuthController.cs processes the request and initiates a token request against Microsoft Entra ID via the Challenge()
method:
[HttpGet("login")]
public ActionResult Login(string? postLoginRedirectUri)
{
string redirectUri = !string.IsNullOrEmpty(postLoginRedirectUri) ? HttpUtility
.UrlDecode(postLoginRedirectUri) : "/";
var props = new AuthenticationProperties { RedirectUri = redirectUri };
return Challenge(props);
}
Once the authentication is successful, the authentication state can be shared with the frontend. The claims in the user's ID token is sent back to the frontend to update the UI via the /api/auth/account
endpoint.
The sample makes use of HTTP only, strict cookies to secure the calls between the frontend and the backend. The default ASP.NET Core authentication cookie behavior will attempt to redirect unauthenticated requests to the identity provider (in this case, Microsoft Entra ID). As this is not the desired behavior in BFF proxy architecture, custom cookie authenticated events is used to modify the default behavior (see CustomCookieAuthenticationEvents.cs).
// Configure cookie properties for ASP.NET Core cookie authentication.
builder.Services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options => {
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Events = new CustomCookieAuthenticationEvents();
});
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 in Preview. 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 these challenges when they are thrown by the web API
This sample app declares that it's CAE-capable by adding the ClientCapabilities
field to the configuration in appsettings.json:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "[Enter 'common', or 'organizations' or the Tenant Id obtained from the Microsoft Entra admin center]",
"ClientId": "[Enter the Client Id aka Application ID obtained from the Microsoft Entra admin center]",
"ClientSecret": "[Copy the client secret added to the app from the Microsoft Entra admin center]",
"ClientCapabilities": [ "CP1" ],
"CallbackPath": "/api/auth/signin-oidc",
"SignedOutCallbackPath": "/api/auth/signout-oidc"
},
}
When a CAE event occurs, the Graph service will throw an exception. You can catch this exception and retrieve the claims challenge inside. Here, we set the challenge as a session variable, and a 401 status is sent to the frontend afterwards, indicating that another login request must be made:
catch (ServiceException svcex) when (svcex.Message.Contains("Continuous access evaluation"))
{
string claimsChallenge = WwwAuthenticateParameters
.GetClaimChallengeFromResponseHeaders(svcex.ResponseHeaders);
// Set the claims challenge string to session, which will be used during the next login request
HttpContext.Session.SetString("claimsChallenge", claimsChallenge);
return Unauthorized("Continuous access evaluation resulted in claims challenge\n" + svcex.Message);
}
Next time when a login request is made to the backend, the claims challenge is retrieved from the session, and is used to present the user with a prompt for satisfying the challenge via Microsoft Entra authorization endpoint.
[HttpGet("login")]
public ActionResult Login(string? postLoginRedirectUri)
{
string redirectUri = !string.IsNullOrEmpty(postLoginRedirectUri) ? HttpUtility
.UrlDecode(postLoginRedirectUri) : "/";
string claims = HttpContext.Session.GetString("claimsChallenge") ?? "";
var props = new AuthenticationProperties { RedirectUri = redirectUri };
if (!string.IsNullOrEmpty(claims))
{
props.Items["claims"] = claims;
HttpContext.Session.Remove("claimsChallenge"); // discard the challenge
}
return Challenge(props);
}
Client apps should treat access tokens as opaque strings, as the contents of the token are intended for the resource only (such as a web API or Microsoft Graph). For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using a site like jwt.ms.
For more details on what's inside the access token, clients should use the token response data that's returned with the access token to your client. When your client requests an access token, the Microsoft identity platform also returns some metadata about the access token for your app's consumption. This information includes the expiry time of the access token and the scopes for which it's valid. For more details about access tokens, please see Microsoft identity platform access tokens
To make bearer token calls to the Microsoft Graph API, Microsoft.Identity.Web makes use of the Microsoft Graph SDK internally. This is shown in Program.cs:
// Add services to the container.
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(builder.Configuration.GetSection("DownstreamApi:Scopes").Value.Split(' '))
.AddMicrosoftGraph(builder.Configuration.GetValue<string>("DownstreamApi:BaseUrl"), builder.Configuration.GetValue<string>("DownstreamApi:Scopes"))
.AddInMemoryTokenCaches();
The service can then be injected into controllers to make Graph calls afterwards. See ProfileController.cs for more.
There is one web app in this sample. To deploy it to Azure App Services, you'll need to:
- create an Azure App Service
- publish the projects to the App Services, and
- update its client(s) to call the website instead of the local environment.
Follow the link to Publish with Visual Studio.
- Install the Visual Studio Code extension Azure App Service.
- Follow the link to Publish with Visual Studio Code
- Navigate back to to the Microsoft Entra admin center. In the left-hand navigation pane, select the Microsoft Entra ID service, and then select App registrations.
- In the resulting screen, select the
CallGraphBFF
application. - In the app's registration screen, select Authentication in the menu.
- In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
https://callgraphbff.azurewebsites.net/api/auth/signin-oidc
https://callgraphbff.azurewebsites.net/api/auth/signout-oidc
- In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
⚠️ 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.
Learn how to:
- Change your app to sign-in users from any organization or Microsoft accounts
- Enable users from National clouds to sign-in to your application
- Enable your web app to call a web API on behalf of the signed-in user
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 (Microsoft Entra ID for developers)
- Microsoft Entra ID 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 Microsoft Entra application consent experiences
- Understand user and admin consent
- Application and service principal objects in Microsoft Entra ID
- Authentication Scenarios for Microsoft Entra ID
- Building Zero Trust ready apps
- National Clouds
- Microsoft.Identity.Web