DotNet Core 3.1 身份验证:oauth 状态丢失或无效

DotNet Core 3.1 Authentication: The oauth state was missing or invalid

我不断收到 The oauth state was missing or invalid in my Staging server 但此代码在我的本地托管 IIS 中运行良好。

P.s。在我被发送到重复页面之前,我已经尝试了 Whosebug 中的所有页面并且我已经查看了所有页面 google。我删除了 CallbackPath,它也坏了:

我在 IIS 7 中将 AWS 负载均衡器与应用程序 运行 的两个实例一起使用。

错误:ArgumentException:必须提供 'CallbackPath' 选项。 (参数'CallbackPath')

DotNet 代码:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.MinimumSameSitePolicy = SameSiteMode.Lax;
        })
        .AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "SportsEngine";
        })
        .AddCookie()
        .AddOAuth("SportsEngine", options =>
        {
            // Client Info
            options.ClientId = Configuration["SSO:SeApiClientId"];
            options.ClientSecret = Configuration["SSO:SeApiClientSecret"];
            options.CallbackPath = new PathString("/oauth/authorize");

            // Client Endpoints
            options.AuthorizationEndpoint = Configuration["SSO:SSOAuthority"];
            options.TokenEndpoint = Configuration["SSO:SSOTokenEndpoint"];

            // Save token
            options.SaveTokens = true;

            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            // TODO: Need to figure out how to add SeriLog in here
        });

        services.AddResponseCaching();
        services.AddControllersWithViews();
        services.AddScoped<IContextFactory, DbContextFactory>();
    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            //logger.LogInformation("In Development.");
            app.UseDeveloperExceptionPage();              
        }
        else
        {
            //logger.LogInformation("Not Development.");
            app.UseExceptionHandler("/Home/Error");
            var forwardingOptions = new ForwardedHeadersOptions()
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            };
            forwardingOptions.KnownNetworks.Clear(); // Loopback by default, this should be temporary
            forwardingOptions.KnownProxies.Clear(); // Update to include

            app.UseForwardedHeaders(forwardingOptions);

            // 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.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        // Auth
        app.UseCookiePolicy();

        app.UseAuthentication();
        app.UseAuthorization();

        // add caching to pipe
        app.UseResponseCaching();

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

        app.UseSerilogRequestLogging(options =>
        {
            // Customize the message template
            options.MessageTemplate = "Handled {RequestPath}";

            // Emit debug-level events instead of the defaults
            options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;

            // Attach additional properties to the request completion event
            options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
            {
                diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
                diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
            };
        });
    }

堆栈跟踪

    2021-09-08 21:19:21.154 +00:00 [WRN] No XML encryptor configured. Key {c83f05de-c4ba-4fc0-b4d6-f550329e41ef} may be persisted to storage in unencrypted form.
2021-09-08 21:19:21.695 +00:00 [INF] Application started. Press Ctrl+C to shut down.
2021-09-08 21:19:21.695 +00:00 [INF] Hosting environment: testdrive
2021-09-08 21:19:21.696 +00:00 [INF] Content root path: C:\Octopus\Applications\Testdrive\Machine.MVC[=11=].0.1995
2021-09-08 21:19:21.786 +00:00 [INF] Request starting HTTP/1.1 GET http://stagingmachine.xyz/oauth/authorize?code=b758c76d24011e86e4c68d9cec728072&state=CfDJ8KjLM7huDtpBl3WGRqwXMZXawockkQzpDjTluDmfzmzN2R2GNrBg7fj0LbsIZavTGXsBscbDxLfjRtXf_8WPCIVUm-FtBiq0lx8jC09ZiXPS_uciWJ0GLcL73Xj3S0kXU8-bgekYUkOfN9UykxIIYLQe9tUeX2RpDWn4Aj5R0BoEJJt-h3jmYaaQwzFAtnQJHbmVWmfA64x01igEan_F6rE  
2021-09-08 21:19:22.072 +00:00 [INF] Error from RemoteAuthentication: The oauth state was missing or invalid..
2021-09-08 21:19:22.082 +00:00 [ERR] An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
 ---> System.Exception: The oauth state was missing or invalid.
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
2021-09-08 21:19:22.188 +00:00 [INF] No cached response available for this request.
2021-09-08 21:19:22.191 +00:00 [INF] Executing endpoint 'Machine.MVC.Controllers.HomeController.Error (Machine.MVC)'
2021-09-08 21:19:22.253 +00:00 [INF] Route matched with {action = "Error", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Error() on controller Machine.MVC.Controllers.HomeController (Machine.MVC).
2021-09-08 21:19:22.355 +00:00 [INF] Executing ViewResult, running view Error.
2021-09-08 21:19:22.532 +00:00 [INF] Executed ViewResult - view Error executed in 207.3459ms.
2021-09-08 21:19:22.536 +00:00 [INF] Executed action Machine.MVC.Controllers.HomeController.Error (Machine.MVC) in 279.6243ms
2021-09-08 21:19:22.536 +00:00 [INF] Executed endpoint 'Machine.MVC.Controllers.HomeController.Error (Machine.MVC)'
2021-09-08 21:19:22.538 +00:00 [INF] The response could not be cached for this request.
2021-09-08 21:19:22.569 +00:00 [INF] Request finished in 796.8368ms 500 text/html; charset=utf-8
2021-09-08 21:19:22.737 +00:00 [INF] Request starting HTTP/1.1 GET http://stagingmachine.xyz/oauth/img/footer/twitter.png  
2021-09-08 21:19:22.737 +00:00 [INF] Request starting HTTP/1.1 GET http://Stagingmachine.xyz/oauth/img/footer/facebook.png  
2021-09-08 21:19:22.742 +00:00 [INF] No cached response available for this request.
2021-09-08 21:19:22.742 +00:00 [INF] No cached response available for this request.
2021-09-08 21:19:22.746 +00:00 [INF] The response could not be cached for this request.
2021-09-08 21:19:22.746 +00:00 [INF] The response could not be cached for this request.
2021-09-08 21:19:22.750 +00:00 [INF] Request finished in 13.9281ms 404 
2021-09-08 21:19:22.750 +00:00 [INF] Request finished in 13.3817ms 404 

当您使用负载均衡时,您需要确保发出初始身份验证请求的客户端实例与使用授权码处理回调的客户端实例相同。客户端需要记住调用之间的状态参数。