Google Auth:"oauth状态丢失或无效。未知位置"

问题描述 投票:0回答:1

我试图在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的授权网址,它和我的本地网址完全一致。

http:/localhost:5000asignin-callback。

当我选择一个帐户授权形式的谷歌,我得到的错误,但如果我添加了

[Route("Account")]

路由到控制器,然后一切正常。我不明白为什么添加账户路由会有不同?有什么办法可以解决这个问题吗?

authentication asp.net-core google-authentication
1个回答
1
投票

我也遇到了同样的问题,最后,我设法解决了这个问题。问题是 googleOptions.CallbackPath 不是 是一个API端点,在登录后会继续执行,是一个内部端点,用于一些内部认证逻辑。你的 回调端点,你必须用另一种方式来实现。

更多细节在这里 https:/github.comdotnetaspnetcoreissues22125。

但为了让长话短说--离开 googleOptions.CallbackPath 不变,并将返回网址作为参数使用 AuthenticationProperties

© www.soinside.com 2019 - 2024. All rights reserved.