Skip to content

Latest commit

 

History

History
436 lines (317 loc) · 24.6 KB

File metadata and controls

436 lines (317 loc) · 24.6 KB
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
csharp
javascript
microsoft-entra-id
microsoft-identity-web
active-directory-aspnetcore-webapp-openidconnect-v2
services
ms-identity
platform
.NET Core
endpoint
Microsoft Entra ID v2.0
level
300
client
ASP.NET Core web app
service
Microsoft Graph

React SPA with ASP.NET Core backend calling Microsoft Graph using the backend for frontend (BFF) proxy architecture

Build status

Overview

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

Scenario

  1. The client-side React SPA initiates token acquisition by calling the login endpoint of the ASP.NET core web app.
  2. 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.
  3. 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.
  4. 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)
Loading

Prerequisites

Setup the sample

Step 1: Clone or download this repository

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.

Step 2: Navigate to project folder

    cd 2-WebApp-graph-user/2-6-BFF-Proxy

Step 3. Trust development certificates

   dotnet dev-certs https --clean
   dotnet dev-certs https --trust

For more information and potential issues, see: HTTPS in .NET Core.

Step 4: Register the sample application(s) in your tenant

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)

Choose the Microsoft Entra tenant where you want to create your applications

To manually register the apps, as a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center.
  2. 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.

Register the client app (CallGraphBFF)

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. In the Register an application page that appears, enter your application's registration information:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example CallGraphBFF.
    2. Under Supported account types, select Accounts in this organizational directory only
    3. Select Register to create the application.
  4. 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.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Web option.
    1. In the Redirect URI section enter the following redirect URI:
      1. https://localhost:7000/api/auth/signin-oidc
      2. https://localhost:7000/api/auth/signout-oidc
    2. Click Save to save your changes.
  7. 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.
  8. In the Client secrets section, select New client secret:
    1. Type a key description (for instance app secret).
    2. Select one of the available key durations (6 months, 12 months or Custom) as per your security posture.
    3. The generated key value will be displayed when you select the Add button. Copy and save the generated value for use in later steps.
    4. 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.

  9. Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
    1. 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:
    2. Select the Add a permission button and then:
    3. Ensure that the Microsoft APIs tab is selected.
    4. In the Commonly used Microsoft APIs section, select Microsoft Graph
    5. In the Delegated permissions section, select User.Read in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.
Configure Optional Claims
  1. Still on the same app registration, select the Token configuration blade to the left.
  2. Select Add optional claim:
    1. Select optional claim type, then choose ID.
    2. 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.

    1. Select Add to save your changes.
Configure the client app (CallGraphBFF) to use your app registration

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".

  1. Open the 2-6-BFF-Proxy/appsettings.json file.
  2. Find the string Enter_the_Tenant_Id_Here and replace it with your Microsoft Entra tenant/directory ID.
  3. Find the string Enter_the_Application_Id_Here and replace it with the application ID (clientId) of CallGraphBFF app copied from the Microsoft Entra admin center.
  4. Find the string Enter_the_Client_Secret_Here and replace it with the generated secret that you saved during the creation of CallGraphBFF copied from the Microsoft Entra admin center.

Step 5: Running the sample

From your shell or command line, execute the following commands:

    cd 2-WebApp-graph-user/2-6-BFF-Proxy/
    dotnet run

Explore the sample

  1. Open your browser and navigate to https://localhost:7000.
  2. Select the Login button on the navigation bar to sign-in.
  3. Select the Profile button on the navigation bar to call Microsoft Graph.

Screenshot Image

ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

Troubleshooting

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.

About the code

Login and logout

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.

Cookie policies

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();
});

Handle Continuous Access Evaluation (CAE) challenge from Microsoft Graph

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:

  1. Declaring that the client app is capable of handling claims challenges.
  2. Processing these challenges when they are thrown by the web API

Declare the CAE capability in the configuration

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"
  },
}

Processing the CAE challenge from Microsoft Graph

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);
}

Access token validation

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

Calling Microsoft Graph

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.

Deploying Web app to Azure App Service

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.

Publish your files (CallGraphBFF)

Publish using Visual Studio

Follow the link to Publish with Visual Studio.

Publish using Visual Studio Code
  1. Install the Visual Studio Code extension Azure App Service.
  2. Follow the link to Publish with Visual Studio Code

Update the Microsoft Entra app registration (CallGraphBFF)

  1. 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.
  2. In the resulting screen, select the CallGraphBFF application.
  3. In the app's registration screen, select Authentication in the menu.
    1. In the Redirect URIs section, update the reply URLs to match the site URL of your Azure deployment. For example:
      1. https://callgraphbff.azurewebsites.net/api/auth/signin-oidc
      2. https://callgraphbff.azurewebsites.net/api/auth/signout-oidc

⚠️ 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.

Next Steps

Learn how to:

Contributing

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.

Learn More