Jabo
Jabo

Reputation: 101

"There was an error trying to log you in: '' " Blazor WebAssembly using IdentiyServer Authentication

I have a Blazor WebAssembly app using IdentityServer that comes with the template as my authentication service. I am having an issue where some users are seeing "There was an error trying to log you in: ''" once they try to login. I had users clear cookies and cache, and they are still experiencing this problem in all their browsers. The weird thing is that most users are able to login, but only a small percent is getting that error. Another odd thing is that it seems like if they use another device such as a phone, another pc, or ipad it works. What could be causing this issue? I have been having trouble trying to debug this issue as I am not able to replicate it on my end and so far not seeing any logs to get any info.

This app is hosted in Google Cloud Platform using linux Docker container.

Thank you in advance

Edit: Here is my startup class

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");
        });
    }
}

Upvotes: 10

Views: 9589

Answers (7)

J S
J S

Reputation: 899

With the version of .NET 7, to fix this error "there was an error trying to log you in 500" - you need to apply migrations and create a database - otherwise, this out-of-the-box solution won't work.

Upvotes: 1

Roma Rudiak
Roma Rudiak

Reputation: 323

Had this issue when using Blazor WASM hosted by ASP.NET 6 application and configured OIDC with Openiddict.

Issue was solved by remapping UserOption for OpenIddict default claims.

// Blazor WASM Program.cs

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-authentication-library?view=aspnetcore-6.0&tabs=visual-studio
builder.Services.AddOidcAuthentication(options =>
{
  builder.Configuration.Bind("Oidc", options.ProviderOptions);
 
  // Set mapping for claims fixed issue
  options.UserOptions.NameClaim = "name";
  options.UserOptions.RoleClaim = "role";
  options.UserOptions.ScopeClaim = "scope";
});

await builder.Build().RunAsync();

Upvotes: 2

Nathan Gallete
Nathan Gallete

Reputation: 168

Who have this problem when publishing on IIS with a self-signed certificate, it may be caused by auth of Application Pool on read the Certificate.

For solve this problem, open certification manager, right click on the certificate, all tasks, private key manager and insert IIS group (IIS_IUSRS) for read/write permission. For test, try "Everyone".

Upvotes: 2

ravi
ravi

Reputation: 1019

Got the same error when using Cognito UserPools with OIDC. The reason for me was, the profile checkbox was not selected in the App Client Settings.

App Client Settings

Upvotes: 0

rayder2007
rayder2007

Reputation: 81

We also faced this problem. The error appears if the server time does not match the client time. Experiments have shown that it is enough to have a difference of 10 minutes. Ideally, the time on the client and server should be in sync. We are currently asking customers to check the time on the device, but this is not a solution to the problem.

Upvotes: 8

Cristovao Morgado
Cristovao Morgado

Reputation: 311

I believe you have to configure you Identity on appsettings.json

On dev you have

"IdentityServer": {
    "Clients": {
      "updown": {
        "Profile": "IdentityServerSPA"
      }

    },
    "Key": {
      "Type": "Development"
    }

But in production you must configure some certificates.

 "Key": {
      "Type": "File",
      "FilePath": "path to .pfx",
      "Password": "pass"
    }
 

otherwise not recommended put the tempkey.json from obj folder

Upvotes: 0

nahidf
nahidf

Reputation: 2394

You need SameSite as None for OpenID Connect to work in this case. Also you need to have HTTPS.

Read more https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1

Upvotes: 0

Related Questions