c# - "There was an error trying to log you in: ' ' "Blazor WebAssembly 使用 IdentiyServer 身份验证

标签 c# asp.net-core identityserver4 blazor blazor-webassembly

我有一个使用 IdentityServer 的 Blazor WebAssembly 应用程序,该应用程序随模板一起作为我的身份验证服务。我遇到了一些用户在尝试登录时看到“尝试登录时出错:''”的问题。我让用户清除了 cookie 和缓存,但他们仍然在所有浏览器中遇到这个问题。奇怪的是,大多数用户都可以登录,但只有一小部分用户会遇到该错误。另一个奇怪的事情是,如果他们使用其他设备,例如手机、另一台电脑或 ipad,它似乎可以工作。什么可能导致这个问题?我在尝试调试这个问题时遇到了麻烦,因为我无法在我的一端复制它,到目前为止还没有看到任何日志来获取任何信息。
此应用程序使用 linux Docker 容器托管在 Google Cloud Platform 中。
先感谢您
编辑:这是我的启动类

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    private const string XForwardedPathBase = "X-Forwarded-PathBase";
    private const string XForwardedProto = "X-Forwarded-Proto";

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("https://www.fakedomainexample.com",
                                                      "https://fakedomainexample.com");
                              });
        });

        services.AddHttpContextAccessor();

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySql(
                Configuration.GetConnectionString("ConnectionString")));

        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        // For some reason, I need to explicitly assign the IssuerUri or else site gets invalid_issuer error
        services.AddIdentityServer(x => x.IssuerUri = "https://www.fakedomainexample.com").AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
            options.IdentityResources["openid"].UserClaims.Add("name");
            options.ApiResources.Single().UserClaims.Add("name");
            options.IdentityResources["openid"].UserClaims.Add("role");
            options.ApiResources.Single().UserClaims.Add("role");
        });
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings.
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 8;
            options.Password.RequiredUniqueChars = 1;

            // User settings.
            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            options.User.RequireUniqueEmail = true;
            options.SignIn.RequireConfirmedAccount = false;
        });

        // Added Cookie options below to fix an issue with login redirect in Chrome for http
        // https://stackoverflow.com/questions/60757016/identity-server-4-post-login-redirect-not-working-in-chrome-only
        // This one worked: https://stackoverflow.com/questions/63449387/cannot-redirect-back-to-angular-client-after-login-in-identity-server
        services.ConfigureExternalCookie(option =>
        {
            option.LoginPath = "/Account/Login";
            option.Cookie.IsEssential = true;
            option.Cookie.SameSite = SameSiteMode.Lax;
        });
        services.ConfigureApplicationCookie(option =>
        {
            option.LoginPath = "/Account/Login";
            option.Cookie.IsEssential = true;
            option.Cookie.SameSite = SameSiteMode.Lax;
        });


        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        app.UseRewriter(new RewriteOptions()
            .AddRedirectToWwwPermanent());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseWebAssemblyDebugging();
        }
        else
        {
            app.UseExceptionHandler("/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.Use((context, next) =>
        {
            if (context.Request.Headers.TryGetValue(XForwardedPathBase, out StringValues pathBase))
            {
                context.Request.PathBase = new PathString(pathBase);
            }

            if (context.Request.Headers.TryGetValue(XForwardedProto, out StringValues proto))
            {
                context.Request.Scheme = proto;
            }
        //context.SetIdentityServerOrigin("https://www.fakedomainexample.com"); 
        return next();
        });
        app.UseHttpsRedirection();
        app.UseBlazorFrameworkFiles();
        
        const string cacheMaxAge = "3600";
        app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                ctx.Context.Response.Headers.Add("Cache-Control", $"public, max-age={cacheMaxAge}");
            }
        });
        app.UseCookiePolicy(new CookiePolicyOptions
        {
            MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Lax,
        });

        app.UseRouting();
        app.UseCors(MyAllowSpecificOrigins);

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");
        });
    }
}

最佳答案

我们也遇到了这个问题。如果服务器时间与客户端时间不匹配,则会出现该错误。实验表明,有10分钟的差异就足够了。
理想情况下,客户端和服务器上的时间应该同步。
我们目前要求客户检查设备上的时间,但这不是问题的解决方案。

关于c# - "There was an error trying to log you in: ' ' "Blazor WebAssembly 使用 IdentiyServer 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64759626/

相关文章:

c# - WCF - 无法解析 [WebGet] 符号 - 我做错了什么?

asp.net-core - C# 核心的 Docker 构建需要互联网连接

.net - PasswordSignInAsync卡在.Core App中

asp.net-core - IdentityServer4 密码授予

java - 具有 Web API 的 JWT Introspection 中间件 - Java 和 Identity Server

c# - 使用 web.config 的角色管理提供程序?

c# - 从富文本框控件获取当前滚动位置?

c# - 将 IdentityServer4 与 WebApplicationFactory 集成测试结合使用

c# - SQL 和 C# 中的哈希不同?

asp.net-core - .NET Core .dll 找不到或打开符号文件