Google Auth:"oauth状态丢失或无效.未知位置" [英] Google Auth: "The oauth state was missing or invalid. Unknown location"

查看:348
本文介绍了Google Auth:"oauth状态丢失或无效.未知位置"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to set up Google Auth on ASP.NET Core 3 and I get this error:

oauth状态丢失或无效.未知位置

The oauth state was missing or invalid. Unknown location

我的Startup.cs文件如下:

My Startup.cs file looks like this:

     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中的授权网址,它与我的本地网址完全匹配:

The authorization url in google is below, it matches my local URL perfectly:

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

当我选择一个帐户来授权Google表单时,我会收到错误消息,但是如果我添加

When I select an account to authorize form google I get the error, but if I add

[Route("Account")]

到控制器的路由,然后一切正常.我不明白为什么添加帐户"路由会有所不同?知道幕后到底是怎么回事吗?

the route to the controller then everything works fine. I can't understand why adding the Account route makes different? Any idea what is going on under the hood?

推荐答案

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

I had the same problem and finally, I managed to fix it. The problem is that googleOptions.CallbackPath is not an API endpoint the will continue to execute after log in. It's an internal endpoint that serves for some internal auth logic. If you want to change your callback endpoint, you have to do it in another way.

更多详细信息在这里发布 https://github.com/dotnet/aspnetcore/issues/22125

More details are here in issue https://github.com/dotnet/aspnetcore/issues/22125

但总而言之-保留googleOptions.CallbackPath不变,并使用AuthenticationProperties

But to make a long story short - leave googleOptions.CallbackPath unchanged and pass return url as parameter using AuthenticationProperties

这篇关于Google Auth:"oauth状态丢失或无效.未知位置"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆