【问题标题】:The oauth state was missing or invalid - Unknown locationoauth 状态丢失或无效 - 未知位置
【发布时间】:2023-01-31 18:09:11
【问题描述】:

我在我的 .NET 7.0 应用程序中同时使用了 Google 和 Facebook 身份验证机制,它们都在本地运行良好。在我的 DEV 环境中部署时,从 Google/Facebook 返回时出现异常。所以挑战工作正常,我可以在他们这边进行身份验证,但回调失败,说:

Exception: The oauth state was missing or invalid.
Unknown location

我被重定向到https://my.website.com/signin-google,状态在查询字符串参数中。这是预期的行为,因为我没有配置显式回调路径,默认情况下它设置为 signin-google 和 signin-facebook。但不知何故,RemoteAuthenticationHandler 似乎不认为这与回调路径匹配,所以它没有处理请求?还是问题出在OAuthHandler.HandleRemoteAuthenticateAsync?也许在取消保护状态数据时?但是为什么这会在本地起作用呢?

我的设置:

services.AddAuthentication()
    .AddGoogle("google", options =>
    {
        options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
        options.ClientId = AppSettings.Instance.GoogleClientId;
        options.ClientSecret = AppSettings.Instance.GoogleClientSecret;
    })
    .AddFacebook("facebook", options =>
    {
        options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
        options.AppId = AppSettings.Instance.FacebookAppId;
        options.AppSecret = AppSettings.Instance.FacebookAppSecret;
    });

编辑:这是否可能与我在 DEV 环境中使用 2 个服务器的事实有关,并且它使用与机器相关的东西来取消保护状态,所以当我登陆另一台机器时它不起作用?

【问题讨论】:

    标签: asp.net-core authentication oauth google-oauth .net-7.0


    【解决方案1】:

    事实证明这是因为我现在将应用程序部署在多个分布式服务器上,通过负载均衡器访问。 这篇文章here 帮助我理解了数据保护在 ASP.NET Core 中的工作原理。

    默认使用密钥轮换系统,密钥由机器生成并保存到%LOCALAPPDATA%ASP.NETDataProtection-Keys。因此,当您扩展应用程序时,这当然不再起作用。

    因此,我决定将数据保护密钥存储在共享数据库中,这样所有机器都将使用相同的密钥:

    1. 添加对 Nuget Microsoft.AspNetCore.DataProtection.EntityFrameworkCore 的引用。

    2. 创建一个继承自 IDataProtectionKeyContext 的 DbContext

    3. 注册你的 DbContext

    4. 设置您的数据保护以将 DbContext 用作:

      builder.Services.AddDataProtection()
          .PersistKeysToDbContext<DataProtectionKeyContext>();
      

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 2017-09-22
      • 1970-01-01
      • 2021-11-06
      • 2021-04-26
      • 2019-02-02
      • 2021-11-12
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多