【问题标题】:The oauth state was missing or invalid, but only happens in azure sometimesoauth 状态丢失或无效,但有时仅在 azure 中发生
【发布时间】:2026-01-20 02:20:03
【问题描述】:

这是我遇到过的最棘手的问题之一。

我有一个在 Docker 容器中运行的 .net5 应用程序,在 Azure Web 应用程序中。 这是我的 Startup.cs 文件:

public class Startup
{
    public Startup(
        IConfiguration configuration,
        IWebHostEnvironment hostingEnvironment)
    {
        this.Configuration = configuration;
        this.HostingEnvironment = hostingEnvironment;
    }

    public IConfiguration Configuration { get; }
    public IWebHostEnvironment HostingEnvironment { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(
        IServiceCollection services)
    {
        services.AddRepositories(this.Configuration);
        services.AddSettings(this.Configuration);
        services.AddServices();
        services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddControllersWithViews();

        services.AddRazorPages(options =>
        {
            options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
            options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
        });

        services.Configure<ForwardedHeadersOptions>(options =>
        {

            options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
         });

         services.ConfigureApplicationCookie(options =>
         {
             options.LoginPath = $"/Identity/Account/Login";
             options.LogoutPath = $"/Identity/Account/Logout";
             options.AccessDeniedPath = $"/Identity/Account/AccessDenied";

         }); 


        services.AddAuthentication().AddGoogle(options =>
        {
            var googleAuthNSection =
                this.Configuration.GetSection("AppSettings:Authentication:Google");

            options.ClientId = googleAuthNSection["ClientId"];
            options.ClientSecret = googleAuthNSection["ClientSecret"];
            options.CorrelationCookie.SameSite = SameSiteMode.Lax;
        })
        ;
            
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILogger<Startup> logger)
    {
        app.UseForwardedHeaders();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        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();
        }

        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            logger.LogInformation("Starting Migration");
            using var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
            logger.LogInformation("Finished Migration");
        }

        app.UseStaticFiles();

        app.UseRouting();

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

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

            endpoints.MapRazorPages();
        });
    }
}

问题:在大多数情况下,应用程序运行平稳。但是,有时它会意外失败并出现以下错误:

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.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)

我有时会说,因为应用程序会运行几天而没有问题,然后随机返回这个错误几个小时。然后它又恢复正常工作了。

如果我出于调试目的启动本地应用服务器,则应用每次都按预期运行。

这可能是天蓝色资源问题吗?还是我达到了 Google API 允许的最大调用数?一次只有我和另一个人在访问该应用程序,而且我们不经常使用它。

谢谢

【问题讨论】:

    标签: c# asp.net .net azure asp.net-core


    【解决方案1】:

    从一开始,您就可以使用带有或不带有 ASP.NET 外部身份提供者/社交登录的身份框架。应该是这样设置的authentication without identity

    public void ConfigureServices(IServiceCollection services)  
    {  
    // requires  
    // using Microsoft.AspNetCore.Authentication.Cookies;  
    // using Microsoft.AspNetCore.Authentication.Google;  
    // NuGet package Microsoft.AspNetCore.Authentication.Google  
    services  
    .AddAuthentication(options =>  
    {  
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;  
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;  
    })  
    .AddCookie()  
    .AddGoogle(options =>  
    {  
    options.ClientId = Configuration["Authentication:Google:ClientId"];  
    options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];  
    }); 
    
    services.AddRazorPages();  
    }
    

    控制器的第二个缺陷是这样的:

    return Challenge(new AuthenticationProperties { RedirectUri = "[https://myhost.com/signin-gitlab"](https://myhost.com/signin-gitlab%22 "https://myhost.com/signin-gitlab%22") }, "Gitlab");  
    
    

    与 aspnet-contrib 团队的 MVC 示例应用程序一样,它实际上应该是:

    return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "Gitlab");  
    
    

    用户实际上正在被验证;问题是它们被转发到 OAuth 中间件的内部路由 /signin-gitlab 没有状态或代码参数,而不是主路由/索引操作,导致错误。

    换一种说法,我搞混了:

    • RedirectUri(用户在身份验证后被重定向)
    • 回调 URL(OAuth 应用程序将带有状态和代码的用户重定向到 OAuth 中间件内部路由,默认为 /signin-gitlab、/signin-google、/signin-facebook,但也可以使用选项覆盖.CallbackPath)。

    也许我的困惑源于 GitLab 文档中的回调 url 被称为REDIRECT URI

    感谢Nan Yu SO Link 的启发性帖子。

    例如:没有 ASP.NET Core Identity 的 Facebook、Google 和外部提供商身份验证

    【讨论】:

      最近更新 更多