Bewerken

Delen via


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 work, school, or personal Microsoft account using the ASP.NET Core 6.0 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.
    • The MicrosoftAccount package supports App Registrations created using "Accounts in any organizational directory" or "Accounts in any organizational directory and Microsoft accounts" options by default.
    • To use other options, set AuthorizationEndpoint and TokenEndpoint members of MicrosoftAccountOptions used to initialize the Microsoft Account authentication to the URLs displayed on Endpoints page of the App Registration after it is created (available by clicking Endpoints on the Overview page).
  • Under Redirect URI, enter your development URL with /signin-microsoft appended. For example, https://localhost:5001/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.

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 secret

Store sensitive settings such as the Microsoft Application (client) ID found on the Overview page of the App Registration and Client Secret you created on the Certificates & secrets page with Secret Manager. For this sample, use the following steps:

  1. Initialize the project for secret storage per the instructions at Enable secret storage.

  2. Store the sensitive settings in the local secret store with the secret keys Authentication:Microsoft:ClientId and Authentication:Microsoft:ClientSecret:

    dotnet user-secrets set "Authentication:Microsoft:ClientId" "<client-id>"
    dotnet user-secrets set "Authentication:Microsoft:ClientSecret" "<client-secret>"
    

The : separator doesn't work with environment variable hierarchical keys on all platforms. For example, the : separator is not supported by Bash. The double underscore, __, is:

  • Supported by all platforms.
  • Automatically replaced by a colon, :.

Configure Microsoft Account Authentication

Add the Authentication service to the Program:

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;

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

The AddAuthentication(IServiceCollection, String) overload sets the DefaultScheme property. The AddAuthentication(IServiceCollection, 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.

For more information about configuration options supported by Microsoft Account authentication, see the MicrosoftAccountOptions API reference. This can be used to request different information about the user.

Sign in with Microsoft Account

  • Run the app and select Log in. An option to sign in with Microsoft appears.
  • Select to sign in with Microsoft. You are redirected to Microsoft for authentication. After signing in with your Microsoft Account, you will be prompted to let the app access your info:
  • Select Yes. You are redirected back to the web site where you can set your email.

You are now logged in using your Microsoft credentials.

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 => { ... });

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.

This sample shows you how to enable users to sign in with their work, school, or personal Microsoft account using the ASP.NET Core 3.0 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.
    • The MicrosoftAccount package supports App Registrations created using "Accounts in any organizational directory" or "Accounts in any organizational directory and Microsoft accounts" options by default.
    • To use other options, set AuthorizationEndpoint and TokenEndpoint members of MicrosoftAccountOptions used to initialize the Microsoft Account authentication to the URLs displayed on Endpoints page of the App Registration after it is created (available by clicking Endpoints on the Overview page).
  • Under Redirect URI, enter your development URL with /signin-microsoft appended. For example, https://localhost:5001/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.

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 secret

Store sensitive settings such as the Microsoft Application (client) ID found on the Overview page of the App Registration and Client Secret you created on the Certificates & secrets page with Secret Manager. For this sample, use the following steps:

  1. Initialize the project for secret storage per the instructions at Enable secret storage.

  2. Store the sensitive settings in the local secret store with the secret keys Authentication:Microsoft:ClientId and Authentication:Microsoft:ClientSecret:

    dotnet user-secrets set "Authentication:Microsoft:ClientId" "<client-id>"
    dotnet user-secrets set "Authentication:Microsoft:ClientSecret" "<client-secret>"
    

The : separator doesn't work with environment variable hierarchical keys on all platforms. For example, the : separator is not supported by Bash. The double underscore, __, is:

  • Supported by all platforms.
  • Automatically replaced by a colon, :.

Configure Microsoft Account Authentication

Add the Microsoft Account service to the Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddRazorPages();

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

The AddAuthentication(IServiceCollection, String) overload sets the DefaultScheme property. The AddAuthentication(IServiceCollection, 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.

For more information about configuration options supported by Microsoft Account authentication, see the MicrosoftAccountOptions API reference. This can be used to request different information about the user.

Sign in with Microsoft Account

Run the app and select Log in. An option to sign in with Microsoft appears. When you select on Microsoft, you are redirected to Microsoft for authentication. After signing in with your Microsoft Account, 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.

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 => { ... });

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.