【问题标题】:Google Auth: "The oauth state was missing or invalid. Unknown location"Google Auth:“oauth 状态丢失或无效。位置未知”
【发布时间】:2020-04-14 19:22:04
【问题描述】:

我正在尝试在 ASP.NET Core 3 上设置 Google Auth,但出现此错误:

oauth 状态丢失或无效。位置不明

我的 Startup.cs 文件如下所示:

     public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            public IConfiguration Configuration { get; }

            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services
                    .AddControllersWithViews()
                    .AddRazorRuntimeCompilation();
                services.AddHttpContextAccessor();
                services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
                services.AddSingleton<IPaddleSettingsService, PaddleSettingsService>();
                services.AddScoped<IPaymentProviderService, PaddlePaymentProviderService>();
                services.Configure<AppConstants>(Configuration);

                services
                    .AddAuthentication(o =>
                    {
                        o.DefaultScheme = "Application";
                        o.DefaultSignInScheme = "External";
                    })
                    .AddCookie("Application")
                    .AddCookie("External")
                    .AddGoogle(o =>
                    {
                        o.ClientId = Configuration["GoogleClientId"];
                        o.ClientSecret = Configuration["GoogleClientSecret"];
                        o.CallbackPath = new PathString("/a/signin-callback");
                        o.ReturnUrlParameter = new PathString("/");
                    });
            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }

                app.UseDefaultFiles();
                app.UseStaticFiles();
                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseHttpsRedirection();

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }

控制器:

    [Route("a")]
        /*[Route("Account")]*/ //Adding additional Account route to controller solves the problem. Why?
        public class AccountController : Controller
        {
            private readonly IOptions<AppConstants> _appConstants;
            private readonly IPaymentProviderService _paymentProvider;

            public AccountController(IOptions<AppConstants> appConstants, IPaymentProviderService paymentProvider)
            {
                _appConstants = appConstants;
                _paymentProvider = paymentProvider;
            }


            [Route("signin-google")]
            public IActionResult Signin(string returnUrl)
            {
                return new ChallengeResult(
                    GoogleDefaults.AuthenticationScheme,
                    new AuthenticationProperties
                    {
                        RedirectUri = Url.Action(nameof(GoogleCallback), new { returnUrl })
                    });
            }

            [Route("signin-callback")]
            public async Task<IActionResult> GoogleCallback(string returnUrl)
            {
                var authenticateResult = await HttpContext.AuthenticateAsync("External");

                if (!authenticateResult.Succeeded) return LocalRedirect("/#signinerr");

                var emailClaim = authenticateResult.Principal.FindFirst(ClaimTypes.Email);
                var activeSubscriptions = await _paymentProvider.GetUserActiveSubscriptions(emailClaim.Value);
                if (activeSubscriptions.Length != 0)
                {
                    var activeSubscription = activeSubscriptions.First(a => a.State == "active");
                    SetCookies(emailClaim.Value, activeSubscription.UserId, activeSubscription.SubscriptionId);
                    return LocalRedirect("/");
                }
                ClearCookies();
                return LocalRedirect("/#signinerr");
            }              
        }

google的授权url如下,和我的本地url完美匹配:

http://localhost:5000/a/signin-callback

当我选择一个帐户授权表单谷歌时,我收到错误,但如果我添加

[Route("Account")]

到控制器的路由然后一切正常。我不明白为什么添加 Account 路由会有所不同?知道引擎盖下发生了什么吗?

【问题讨论】:

  • 您是否为自定义Signin 操作配置了LoginPath?它是否可以达到您的自定义Signin 操作?
  • @FeiHan 你能说得更具体一点吗?什么是 LoginPath,我应该在哪里设置它?
  • 在 Startup.cs 中,设置.AddCookie("Application",options=&gt; { options.LoginPath = "/signin-google"; })

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


【解决方案1】:

我遇到了同样的问题,最后,我设法解决了它。问题是 googleOptions.CallbackPath 不是一个 API 端点,登录后将继续执行。 它是一个内部端点,用于一些内部身份验证逻辑。 如果您想更改 您的 回调端点,则必须以另一种方式进行。

更多详情请见 issuehttps://github.com/dotnet/aspnetcore/issues/22125

但长话短说 - 保持 googleOptions.CallbackPath 不变,并使用 AuthenticationProperties 将返回 url 作为参数传递

【讨论】:

  • 在 Google 的 API 控制台中注册 https://your-domain/signin-google 为我解决了问题。重定向到挑战时,googleoptions.CallbackPath 属性留空(根据答案)AuthenticationProperties.RedirectUri = Url.Action("GoogleCallback")。因此,在 Google 的控制台中设置了两个端点——起到了作用。感谢您的帮助!
  • 哇。我不敢相信我在这上面浪费了几个小时,哈哈!干杯,伙计,你度过了美好的一天。文档对此并不清楚,或者我错过了一些东西。是的,中间件内部使用了 signin-google 路径。
  • 如果它可以帮助任何人,我已经在此处记录了一些故障排除步骤。 mahdikarimipour.com/blog/…
猜你喜欢
  • 2023-01-31
  • 2017-09-22
  • 1970-01-01
  • 2021-11-06
  • 2021-04-26
  • 2023-02-15
  • 2019-02-02
  • 1970-01-01
  • 2021-11-12
相关资源
最近更新 更多