ASP.NET Core 中的 Google 外部登录设置Google external login setup in ASP.NET Core

作者:Valeriy NovytskyyRick AndersonBy Valeriy Novytskyy and Rick Anderson

本教程演示如何让用户能够使用在前一页上创建的 ASP.NET Core 3.0 项目使用其 Google 帐户登录。This tutorial shows you how to enable users to sign in with their Google account using the ASP.NET Core 3.0 project created on the previous page.

创建 Google API 控制台项目和客户端 IDCreate a Google API Console project and client ID

  • 请安装AspNetCoreInstall Microsoft.AspNetCore.Authentication.Google.
  • 导航到 "将Google 登录集成到你的 web 应用" ,然后选择 "配置项目"。Navigate to Integrating Google Sign-In into your web app and select CONFIGURE A PROJECT.
  • 在 "配置 OAuth 客户端" 对话框中,选择 " Web 服务器"。In the Configure your OAuth client dialog, select Web server.
  • 在 "授权重定向 uri " 文本输入框中,设置重定向 URI。In the Authorized redirect URIs text entry box, set the redirect URI. 例如,https://localhost:44312/signin-googleFor example, https://localhost:44312/signin-google
  • 保存客户端 ID客户端密码Save the Client ID and Client Secret.
  • 部署站点时,从Google 控制台注册新的公共 url。When deploying the site, register the new public url from the Google Console.

存储 Google ClientID 和 ClientSecretStore Google ClientID and ClientSecret

机密管理器存储敏感设置,例如 Google Client IDClient SecretStore sensitive settings such as the Google Client ID and Client Secret with the Secret Manager. 出于本教程的目的,请将令牌命名 Authentication:Google:ClientIdAuthentication:Google:ClientSecretFor the purposes of this tutorial, name the tokens Authentication:Google:ClientId and Authentication:Google:ClientSecret:

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

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

你可以在Api 控制台中管理 api 凭据和使用情况。You can manage your API credentials and usage in the API Console.

配置 Google 身份验证Configure Google authentication

将 Google 服务添加到 Startup.ConfigureServicesAdd the Google service to Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
    services.AddDbContext<ApplicationDbContext>(options =>
    services.AddDefaultIdentity<IdentityUser>(options =>
        options.SignIn.RequireConfirmedAccount = true)

        .AddGoogle(options =>
            IConfigurationSection googleAuthNSection =

            options.ClientId = googleAuthNSection["ClientId"];
            options.ClientSecret = googleAuthNSection["ClientSecret"];

在调用AddIdentity配置的默认方案设置。The call to AddIdentity 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.

用 Google 登录Sign in with Google

  • 运行应用程序,并单击 "登录"Run the app and click Log in. 此时将显示使用 Google 登录的选项。An option to sign in with Google appears.
  • 单击 " google " 按钮,该按钮将重定向到 google 进行身份验证。Click the Google button, which redirects to Google for authentication.
  • 输入 Google 凭据后,会重定向回网站。After entering your Google credentials, you are redirected back to the web site.

使用代理或负载均衡器转发请求信息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 以使用代理服务器和负载均衡器.

多个身份验证提供程序Multiple authentication providers

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

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

有关 Google authentication 支持的配置选项的详细信息,请参阅 GoogleOptions API 参考。See the GoogleOptions API reference for more information on configuration options supported by Google authentication. 这可用于请求有关用户的其他信息。This can be used to request different information about the user.

更改默认回调 URIChange the default callback URI

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


  • 如果登录不起作用,并且没有出现任何错误,请切换到开发模式,以便更轻松地进行调试。If the sign-in doesn't work and you aren't getting any errors, switch to development mode to make the issue easier to debug.
  • 如果未通过在 ConfigureServices中调用 services.AddIdentity 来配置标识,尝试对 ArgumentException 中的结果进行身份验证 :必须提供 "SignInScheme" 选项If Identity isn't configured by calling services.AddIdentity in ConfigureServices, attempting to authenticate results in ArgumentException: The 'SignInScheme' option must be provided. 本教程中使用的项目模板可确保完成此操作。The project template used in this tutorial ensures that this is done.
  • 如果尚未通过应用初始迁移来创建站点数据库,则在处理请求错误时,将会出现数据库操作失败的情况。If the site database has not been created by applying the initial migration, you get A database operation failed while processing the request error. 选择 "应用迁移" 以创建数据库,并刷新页面以继续出现错误。Select Apply Migrations to create the database, and refresh the page to continue past the error.

后续步骤Next steps

  • 本文演示了如何通过 Google 进行身份验证。This article showed how you can authenticate with Google. 您可以遵循类似的方法向前一页上列出的其他提供程序进行身份验证。You can follow a similar approach to authenticate with other providers listed on the previous page.
  • 将应用发布到 Azure 后,请在 Google API 控制台中重置 ClientSecretOnce you publish the app to Azure, reset the ClientSecret in the Google API Console.
  • Authentication:Google:ClientIdAuthentication:Google:ClientSecret 设置为 Azure 门户中的应用程序设置。Set the Authentication:Google:ClientId and Authentication:Google:ClientSecret as application settings in the Azure portal. 配置系统设置为从环境变量读取密钥。The configuration system is set up to read keys from environment variables.