Microsoft Account external login setup with ASP.NET Core

By Valeriy Novytskyy and Rick Anderson

This sample shows you how to enable users to sign in with their Microsoft account using the ASP.NET Core 2.2 project created on the previous page.

Create the app in Microsoft Developer Portal

If you don't have a Microsoft account, select Create one. After signing in you are redirected to the App registrations page:

  • Select New registration
  • Enter a Name.
  • Select an option for Supported account types.
  • Under Redirect URI, enter your development URL with /signin-microsoft appended. For example, https://localhost:44389/signin-microsoft. The Microsoft authentication scheme configured later in this sample will automatically handle requests at /signin-microsoft route to implement the OAuth flow.
  • Select Register

Create client secret

  • In the left pane, select Certificates & secrets.

  • Under Client secrets, select New client secret

    • Add a description for the client secret.
    • Select the Add button.
  • Under Client secrets, copy the value of the client secret.

Note

The URI segment /signin-microsoft is set as the default callback of the Microsoft authentication provider. You can change the default callback URI while configuring the Microsoft authentication middleware via the inherited RemoteAuthenticationOptions.CallbackPath property of the MicrosoftAccountOptions class.

Store the Microsoft client ID and client secret

Run the following commands to securely store ClientId and ClientSecret using Secret Manager:

dotnet user-secrets set Authentication:Microsoft:ClientId <Client-Id>
dotnet user-secrets set Authentication:Microsoft:ClientSecret <Client-Secret>

Link sensitive settings like Microsoft ClientId and ClientSecret to your application configuration using the Secret Manager. For the purposes of this sample, name the tokens Authentication:Microsoft:ClientId and Authentication:Microsoft:ClientSecret.

When working with hierarchical keys in environment variables, a colon separator (:) may not work on all platforms (for example, Bash). A double underscore (__) is supported by all platforms and is automatically replaced by a colon.

Configure Microsoft Account Authentication

Add the Microsoft Account service to Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>()
        .AddDefaultUI(UIFramework.Bootstrap4)
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
    {
        microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
        microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

The call to AddDefaultIdentity configures the default scheme settings. The AddAuthentication(String) overload sets the DefaultScheme property. The AddAuthentication(Action<AuthenticationOptions>) overload allows configuring authentication options, which can be used to set up default authentication schemes for different purposes. Subsequent calls to AddAuthentication override previously configured AuthenticationOptions properties.

AuthenticationBuilder extension methods that register an authentication handler may only be called once per authentication scheme. Overloads exist that allow configuring the scheme properties, scheme name, and display name.

Multiple authentication providers

When the app requires multiple providers, chain the provider extension methods behind AddAuthentication:

services.AddAuthentication()
    .AddMicrosoftAccount(microsoftOptions => { ... })
    .AddGoogle(googleOptions => { ... })
    .AddTwitter(twitterOptions => { ... })
    .AddFacebook(facebookOptions => { ... });

See the MicrosoftAccountOptions API reference for more information on configuration options supported by Microsoft Account authentication. This can be used to request different information about the user.

Sign in with Microsoft Account

Run the and click Log in. An option to sign in with Microsoft appears. When you click on Microsoft, you are redirected to Microsoft for authentication. After signing in with your Microsoft Account (if not already signed in) you will be prompted to let the app access your info:

Tap Yes and you will be redirected back to the web site where you can set your email.

You are now logged in using your Microsoft credentials:

Forward request information with a proxy or load balancer

If the app is deployed behind a proxy server or load balancer, some of the original request information might be forwarded to the app in request headers. This information usually includes the secure request scheme (https), host, and client IP address. Apps don't automatically read these request headers to discover and use the original request information.

The scheme is used in link generation that affects the authentication flow with external providers. Losing the secure scheme (https) results in the app generating incorrect insecure redirect URLs.

Use Forwarded Headers Middleware to make the original request information available to the app for request processing.

For more information, see Configure ASP.NET Core to work with proxy servers and load balancers.

Troubleshooting

  • If the Microsoft Account provider redirects you to a sign in error page, note the error title and description query string parameters directly following the # (hashtag) in the Uri.

    Although the error message seems to indicate a problem with Microsoft authentication, the most common cause is your application Uri not matching any of the Redirect URIs specified for the Web platform.

  • If Identity isn't configured by calling services.AddIdentity in ConfigureServices, attempting to authenticate will result in ArgumentException: The 'SignInScheme' option must be provided. The project template used in this sample ensures that this is done.

  • If the site database has not been created by applying the initial migration, you will get A database operation failed while processing the request error. Tap Apply Migrations to create the database and refresh to continue past the error.

Next steps

  • This article showed how you can authenticate with Microsoft. You can follow a similar approach to authenticate with other providers listed on the previous page.

  • Once you publish your web site to Azure web app, create a new client secrets in the Microsoft Developer Portal.

  • Set the Authentication:Microsoft:ClientId and Authentication:Microsoft:ClientSecret as application settings in the Azure portal. The configuration system is set up to read keys from environment variables.