使用 ASP.NET Core 的 Microsoft 帐户外部登录设置Microsoft Account external login setup with ASP.NET Core

作者:Valeriy NovytskyyRick AndersonBy Valeriy Novytskyy and Rick Anderson

此示例演示如何使用户能够使用在前一页上创建的 ASP.NET Core 2.2 项目使用其 Microsoft 帐户进行登录。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.

在 Microsoft 开发人员门户中创建应用Create the app in Microsoft Developer Portal

如果没有 Microsoft 帐户,请选择 "创建"。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.
  • 在 "重定向 URI" 下,输入/signin-microsoft追加的开发 URL。Under Redirect URI, enter your development URL with /signin-microsoft appended. 例如, https://localhost:44389/signin-microsoftFor example, https://localhost:44389/signin-microsoft. 稍后在本示例中配置的 Microsoft 身份验证方案将自动处理/signin-microsoft路由中的请求以实现 OAuth 流。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.

备注

URI 段/signin-microsoft设置为 Microsoft 身份验证提供程序的默认回调。The URI segment /signin-microsoft is set as the default callback of the Microsoft authentication provider. 通过MicrosoftAccountOptions类的继承的RemoteAuthenticationOptions. CallbackPath属性配置 Microsoft 身份验证中间件时,可以更改默认的回调 URI。You can change the default callback URI while configuring the Microsoft authentication middleware via the inherited RemoteAuthenticationOptions.CallbackPath property of the MicrosoftAccountOptions class.

存储 Microsoft 客户端 ID 和客户端密钥Store the Microsoft client ID and client secret

运行以下命令来安全地存储ClientIdClientSecret使用机密管理器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>

使用机密管理器ClientId敏感ClientSecret设置(如 Microsoft 和应用程序配置)链接起来。Link sensitive settings like Microsoft ClientId and ClientSecret to your application configuration using the Secret Manager. 出于本示例的目的,请将令牌Authentication:Microsoft:ClientId命名为和。 Authentication:Microsoft:ClientSecretFor the purposes of this sample, name the tokens Authentication:Microsoft:ClientId and Authentication:Microsoft:ClientSecret.

在环境变量中使用分层键时,冒号分隔符 (:) 可能无法适用于所有平台(例如 Bash)。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.

配置 Microsoft 帐户身份验证Configure Microsoft Account Authentication

将 Microsoft 帐户服务添加到Startup.ConfigureServicesAdd 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);
}

在调用AddDefaultIdentity配置的默认方案设置。The call to AddDefaultIdentity configures the default scheme settings. AddAuthentication(String)重载集DefaultScheme属性。The AddAuthentication(String) overload sets the DefaultScheme property. AddAuthentication (操作<AuthenticationOptions>)重载允许配置身份验证选项,可用于设置针对不同目的的默认身份验证方案。The AddAuthentication(Action<AuthenticationOptions>) overload allows configuring authentication options, which can be used to set up default authentication schemes for different purposes. 对后续调用AddAuthentication以前配置的重写AuthenticationOptions属性。Subsequent calls to AddAuthentication override previously configured AuthenticationOptions properties.

AuthenticationBuilder注册身份验证处理程序的扩展方法只能调用一次每个身份验证方案。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

如果应用需要多个提供程序,请在 AddAuthentication 后面链接提供程序扩展方法:When the app requires multiple providers, chain the provider extension methods behind AddAuthentication:

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

有关 Microsoft 帐户身份验证支持的配置选项的详细信息,请参阅MicrosoftAccountOptions API 参考。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.

Microsoft 登录帐户Sign in with Microsoft Account

运行,并单击 "登录"Run the and click Log in. 此时会显示一个用于使用 Microsoft 登录的选项。An option to sign in with Microsoft appears. 当你单击 "Microsoft" 时,你将重定向到 Microsoft 进行身份验证。When you click on Microsoft, you are redirected to Microsoft for authentication. 使用你的 Microsoft 帐户登录(如果尚未登录),系统会提示你让应用访问你的信息: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.

你现在已使用 Microsoft 凭据登录: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. 此信息通常包括安全请求方案 (https)、主机和客户端 IP 地址。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. 丢失安全方案 (https) 会导致应用生成不正确且不安全的重定向 URL。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.

有关详细信息,请参阅 配置 ASP.NET Core 以使用代理服务器和负载均衡器For more information, see 配置 ASP.NET Core 以使用代理服务器和负载均衡器.

疑难解答Troubleshooting

  • 如果 Microsoft 帐户提供程序将您重定向到登录错误页面,请在 Uri 中的# (井号)后直接记下错误标题和说明查询字符串参数。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.

    尽管错误消息似乎指出了 Microsoft 身份验证存在问题,但最常见的原因是应用程序 Uri 与为Web平台指定的任何重定向 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.

  • 如果未通过调用services.AddIdentity ConfigureServices来配置标识,尝试进行身份验证将导致ArgumentException:必须提供"SignInScheme" 选项。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

  • 本文演示了如何向 Microsoft 进行身份验证。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.

  • 将网站发布到 Azure web 应用后,在 Microsoft 开发人员门户中创建新的客户端密码。Once you publish your web site to Azure web app, create a new client secrets in the Microsoft Developer Portal.

  • 设置Authentication:Microsoft:ClientIdAuthentication:Microsoft:ClientSecret作为在 Azure 门户中的应用程序设置。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.