I keep getting The oauth state was missing or invalid in my Staging server but this code works just fine in my local hosted IIS.
P.s. Before I get sent to a duplicate page, I have tried all the pages in StackOverflow and I have looked all over google. I removed the CallbackPath and that broke as well:
I am using AWS Load balancer with two instances of the app running in IIS 7.
Error: ArgumentException: The 'CallbackPath' option must be provided. (Parameter 'CallbackPath')
DotNet Code:
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);
};
});
}
Stack Trace
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\0.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
CodePudding user response:
When you use load balancing, you need to make sure the client instance that makes the initial authentication request is the same as the one handling the callback with the authorization code. The client needs to remember the state parameter between the calls.