Skip to content

Web Apps

Jean-Marc Prieur edited this page Jul 13, 2020 · 58 revisions

Important This page is for Microsoft.Identity.Web 0.2.x. For previous versions of the API, see Migrating from Microsoft Identity Web 0.1.x to Microsoft Identity Web 2.x

Why to use Microsoft.Identity.Web in web apps?

Currently, ASP.NET Core web app templates (dot net new mvc -auth) create web apps that sign in users with the Azure AD v1.0 endpoint, allowing users to sign in with their organizational accounts (also called Work or school accounts).

This library adds ServiceCollection and AuthenticationBuilder extension methods for use in the ASP.NET Core web app Startup.cs file. These extension methods enable the web app to sign in users with the Microsoft identity platform and, optionally, enable the web app to call APIs on behalf of the signed-in user.

Usage

Web apps that sign in users - Startup.cs

With Azure AD

Assuming you have a similar configuration in appsettings.json to enable the web app:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "msidentitysamplestesting.onmicrosoft.com",
    "TenantId": "7f58f645-c190-4ce5-9de4-e2b7acd2a6ab",
    "ClientId": "86699d80-dd21-476a-bcd1-7c1a3d471f75",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath ": "/signout-callback-oidc",

    // Only if you want to call an API
    "ClientSecret": "[Copy the client secret added to the app from the Azure portal]"
  },
...
}

To enable users to sign in with the Microsoft identity platform, replace this code in your web application's Startup.cs file:

using Microsoft.Identity.Web;

public class Startup
{
  ...
  public void ConfigureServices(IServiceCollection services)
  {
   ...
   services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
           .AddAzureAD(options => Configuration.Bind("AzureAd", options));
   ...
  }
  ...
}

... by the following code:

using Microsoft.Identity.Web;

public class Startup
{
  ...
  public void ConfigureServices(IServiceCollection services)
  {
   ...
      services.AddMicrosoftWebAppAuthentication(Configuration);
   ...
  }
  ...
}

This method adds authentication with the Microsoft identity platform. This includes validating the token in all scenarios (single- and multi-tenant applications) in the Azure public and national clouds.

Advanced scenarios

Using delegate events

AddMicrosoftWebApp (applied to authentication builders) has another override, which takes delegates instead of a configuration section. The override with a configuration section actually calls the override with delegates. See the source code for AddMicrosoftWebApp with configuration section

In advanced scenarios you might want to add configuration by code, or if you want to subscribe to OpenIdConnect events. For instance if you want to provide a custom processing when the token is validated, you could use code like the following:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftWebApp(options =>
{
    Configuration.Bind("AzureAD", options);
    options.Events ??= new OpenIdConnectEvents();
    options.Events.OnTokenValidated += OnTokenValidatedFunc;
});

with OnTokenValidatedFunc like the following:

private async Task OnTokenValidatedFunc(TokenValidatedContext context)
{
    // Custom code here
    await Task.CompletedTask.ConfigureAwait(false);
}

In the above code, your handler will be executed after any existing handlers. In the below code, your code will be executed before any other existing handlers.

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftWebApp(options =>
{
    Configuration.Bind("AzureAD", options);
    options.Events ??= new OpenIdConnectEvents();
    var existingHandlers = options.Events.OnTokenValidated;
    options.Events.OnTokenValidated = OnTokenValidatedFunc;
    options.Events.OnTokenValidated += existingHandlers;
});

This override also allows you to set an optional delegate to initialize the CookiesAuthenticationOptions.

Specify the authentication scheme

In more advanced scenarios, for instance if you use several IdPs, you might want to specify an authentication scheme (here using the default authentication scheme, which makes this code snippet equivalent to the previous one)

using Microsoft.Identity.Web;

public class Startup
{
  ...
  public void ConfigureServices(IServiceCollection services)
  {
   ...
      services.AddAuthentication("MyAuthenticationScheme")
              .AddMicrosoftWebApp(Configuration, 
                 openIdConnectAuthenticationScheme: "MyAuthenticationScheme");
   ...
  }
  ...
}

Additional resources to sign-in user to a web app with Microsoft identity platform

See also:

With Azure AD B2C

The principle is the same, except that the appsettings.json has generally a section named "AzureAdB2C" (but you can choose the name you want, provided it's consistent with what you use in the AddMicrosoftWebApp method, and you need to declare policies.

{
  "AzureAdB2C": {
    "Instance": "https://fabrikamb2c.b2clogin.com",
    "ClientId": "fdb91ff5-5ce6-41f3-bdbd-8267c817015d",
    "Domain": "fabrikamb2c.onmicrosoft.com",
    "SignedOutCallbackPath": "/signout/B2C_1_susi",
    "SignUpSignInPolicyId": "b2c_1_susi",
    "ResetPasswordPolicyId": "b2c_1_reset",
    "EditProfilePolicyId": "b2c_1_edit_profile", // Optional profile editing policy

The startup.cs file is then:

using Microsoft.Identity.Web;

public class Startup
{
  ...
  public void ConfigureServices(IServiceCollection services)
  {
   ...
      AddMicrosoftWebApp(Configuration, "AzureAdB2C");
   ...
  }
  ...
}

See also:

Web apps that sign in users and call web APIs on behalf of the signed-in user - Startup.cs

If you want your web app to call web APIs, add the .AddMicrosoftWebAppCallsWebApi() line, and then choose a token cache implementation, for example .AddInMemoryTokenCaches():

WebAppBuilderExtensionsMethods

WebAppServiceExtensionsMethods

using Microsoft.Identity.Web;

public class Startup
{
 const string scopesToRequest = "user.read";
  ...
  public void ConfigureServices(IServiceCollection services)
  {
   ...
   services.AddMicrosoftWebAppAuthentication(Configuration)
           .AddMicrosoftWebAppCallsWebApi(Configuration,
                                          new string[] { scopesToRequest })
           .AddInMemoryTokenCaches();
   ...
  }
  ...
}

By default, AddMicrosoftWebAppAuthentication and the override of AddMicrosoftWebApp taking a configuration object get the configuration from the "AzureAD" section of the configuration files. It has several parameters you can change.

The proposed token cache serialization is in memory. You can also use the session cache, or various distributed caches.

Optimization

Note that you don't need to pass-in the scopes to request when calling AddMicrosoftWebAppCallsWebApi. You can do that just in time in the controller (see Web app controller below)

using Microsoft.Identity.Web;

public class Startup
{
  ...
  public void ConfigureServices(IServiceCollection services)
  {
   ...
   services.AddMicrosoftWebAppAuthentication(Configuration)
           .AddWebAppCallsWebApi(Configuration)
           .AddInMemoryTokenCaches();
   ...
  }
  ...
}

Web app controller

For your web app to call web APIs on behalf of the signed-in user, add a parameter of type ITokenAcquisition to the constructor of your controller (the ITokenAcquisition service will be injected by dependency injection by ASP.NET Core).

ITokenAcquisition

using Microsoft.Identity.Web;

[Authorize]
public class HomeController : Controller
{
  readonly ITokenAcquisition tokenAcquisition;

  public HomeController(ITokenAcquisition tokenAcquisition)
  {
   this.tokenAcquisition = tokenAcquisition;
  }
  ...

Then, in your controller actions, call ITokenAcquisition.GetAccessTokenForUserAsync, passing the scopes for which to request a token. The other methods of ITokenAcquisition are used from the AddMicrosoftWebAppCallsWebApi() method and similar methods for web APIs (see below).

[Authorize]
public class HomeController : Controller
{
  readonly ITokenAcquisition tokenAcquisition;
  ...
  [AuthorizeForScopes(Scopes = new[] { "user.read" })]
  public async Task<IActionResult> Action()
  {
   string[] scopes = new []{"user.read"};
   string token = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
   ...
   // call the downstream API with the bearer token in the Authorize header
  }

The controller action is decorated with the AuthorizeForScopesAttribute which enables it to process the MsalUiRequiredException that could be thrown by the service implementing ITokenAcquisition.GetAccessTokenForUserAsync. The web app can then interact with the user and ask them to consent to the scopes, or re-sign in if needed.

AuthorizeForScopes

If your application wants to call a web API on behalf of itself (not of behalf of a user), you can use ITokenAcquisition.GetAccessTokenForAppAsync:

[Authorize]
public class HomeController : Controller
{
  readonly ITokenAcquisition tokenAcquisition;
  ...
  public async Task<IActionResult> Action()
  {
   string[] scopes = new []{"users.read.all"};
   string token = await tokenAcquisition.GetAccessTokenForAppAsync(scopes);
   ...
   // call the downstream API with the bearer token in the Authorize header
  }

Getting started with Microsoft Identity Web

Token cache serialization

Web apps

Web APIs

Daemon scenario

Advanced topics

Extensibility

Credential providers

FAQ

News

Contribute

Other resources

Clone this wiki locally