Quickstart: ASP.NET Core web app that signs in users and calls Microsoft Graph on their behalf

Welcome! This probably isn't the page you were expecting. While we work on a fix, this link should take you to the right article:

Quickstart: Add sign-in with Microsoft to an ASP.NET Core web app

We apologize for the inconvenience and appreciate your patience while we work to get this resolved.

In this quickstart, you download and run a code sample that demonstrates how an ASP.NET Core web app can sign in users from any Microsoft Entra organization and calls Microsoft Graph.

See How the sample works for an illustration.

Step 1: Configure your application in the Azure portal

For the code sample in this quickstart to work, add a Redirect URI of https://localhost:44321/signin-oidc and > Front-channel logout URL of https://localhost:44321/signout-oidc in the app registration.

Already configured Your application is configured with these attributes.

Step 2: Download the ASP.NET Core project

Run the project.

Tip

To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.

Step 3: Your app is configured and ready to run

We have configured your project with values of your app's properties and it's ready to run.

Note

Enter_the_Supported_Account_Info_Here

About the code

This section gives an overview of the code required to sign in users and call the Microsoft Graph API on their behalf. This overview can be useful to understand how the code works, main arguments, and also if you want to add sign-in to an existing ASP.NET Core application and call Microsoft Graph. It uses Microsoft.Identity.Web, which is a wrapper around MSAL.NET.

How the sample works

Diagram that how the sample app generated by this quickstart works.

Startup class

The Microsoft.AspNetCore.Authentication middleware uses a Startup class that's executed when the hosting process initializes:


  public void ConfigureServices(IServiceCollection services)
  {  
    // Get the scopes from the configuration (appsettings.json)
    var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
  
      // Add sign-in with Microsoft
      services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))

            // Add the possibility of acquiring a token to call a protected web API
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)

                // Enables controllers and pages to get GraphServiceClient by dependency injection
                // And use an in memory token cache
                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                .AddInMemoryTokenCaches();

      services.AddControllersWithViews(options =>
      {
          var policy = new AuthorizationPolicyBuilder()
              .RequireAuthenticatedUser()
              .Build();
          options.Filters.Add(new AuthorizeFilter(policy));
      });

      // Enables a UI and controller for sign in and sign out.
      services.AddRazorPages()
          .AddMicrosoftIdentityUI();
  }

The AddAuthentication() method configures the service to add cookie-based authentication, which is used in browser scenarios and to set the challenge to OpenID Connect.

The line containing .AddMicrosoftIdentityWebApp adds the Microsoft identity platform authentication to your application. This is provided by Microsoft.Identity.Web. It's then configured to sign in using the Microsoft identity platform based on the information in the AzureAD section of the appsettings.json configuration file:

appsettings.json key Description >
ClientId Application (client) ID of the application registered in the Azure portal.
Instance Security token service (STS) endpoint for the user to authenticate. This value is typically https://login.microsoftonline.com/, indicating the Azure public cloud.
TenantId Name of your tenant or its tenant ID (a GUID), or common to sign in users with work or school accounts or Microsoft personal accounts.

The EnableTokenAcquisitionToCallDownstreamApi method enables your application to acquire a token to call protected web APIs. AddMicrosoftGraph enables your controllers or Razor pages to benefit directly the GraphServiceClient (by dependency injection) and the AddInMemoryTokenCaches methods enables your app to benefit from a token cache.

The Configure() method contains two important methods, app.UseAuthentication() and app.UseAuthorization(), that enable their named functionality. Also in the Configure() method, you must register Microsoft Identity Web's routes with at least one call to endpoints.MapControllerRoute() or a call to endpoints.MapControllers().

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

// endpoints.MapControllers(); // REQUIRED if MapControllerRoute() isn't called.

Protect a controller or a controller's method

You can protect a controller or its methods by applying the [Authorize] attribute to the controller's class or one or more of its methods. This [Authorize] attribute restricts access by allowing only authenticated users. If the user isn't already authenticated, an authentication challenge can be started to access the controller. In this quickstart, the scopes are read from the configuration file:

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public async Task<IActionResult> Index()
{
    var user = await _graphServiceClient.Me.GetAsync();
    ViewData["ApiResult"] = user?.DisplayName;

    return View();
}

Help and support

If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.

Next steps

The GitHub repo that contains the ASP.NET Core code sample referenced in this quickstart includes instructions and more code samples that show you how to:

  • Add authentication to a new ASP.NET Core web application
  • Call Microsoft Graph, other Microsoft APIs, or your own web APIs
  • Add authorization
  • Sign in users in national clouds or with social identities