Search code examples
c#windowsserverasp.net-core-2.2

502 Bad Gateway / failing on passwordsigninasync call


Microsoft.AspNetCore.Identity.SignInResult loSignInResult = await base._oLoginManager.PasswordSignInAsync(loUser.UserName, lsPassword, true, false);

This is the line that causes the 502 Bad Gateway message.

Please see the startup program below (_bStaging is false when this error occurs), I have tried to reorder the code without success. This error started occurring the other day without a significant code change. No changes were made to the server, and only I have access.:

    public void ConfigureServices(IServiceCollection loServices)
    {
        try
        {
            if (!this._bIsStaging)
            {
                loServices.Configure<MvcOptions>(options =>
                {
                    options.Filters.Add(new RequireHttpsAttribute());
                });
            }
            loServices.AddSession();
            Heron.Data.Classes.ConnectionStrings._sHeronConnectionString = this._oConfiguration.GetConnectionString(this.GetConnectionStringName("Heron"));
            Heron.Data.Classes.ConnectionStrings._sIdentityConnectionString = this._oConfiguration.GetConnectionString(this.GetConnectionStringName("Identity"));
            loServices.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            loServices.AddDbContext<Heron.Data.DB.HeronContext>(O => O.UseSqlServer(Heron.Data.Classes.ConnectionStrings._sHeronConnectionString));
            loServices.AddScoped<DbContext>(sp => sp.GetService<Heron.Data.DB.HeronContext>());
            loServices.AddDbContext<Heron.Data.DB.Extensions.IdentityExtend.DbContext>(O => O.UseSqlServer(Heron.Data.Classes.ConnectionStrings._sIdentityConnectionString));
            loServices.AddScoped<DbContext>(sp => sp.GetService<Heron.Data.DB.Extensions.IdentityExtend.DbContext>());
            loServices.AddIdentity<Heron.Data.DB.Extensions.IdentityExtend.User, Heron.Data.DB.Extensions.IdentityExtend.Role>(opts =>
            {
                opts.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 0, Heron.Library.Classes.Constants._nDefaultLockoutTime, 0);
                opts.Lockout.MaxFailedAccessAttempts = Heron.Library.Classes.Constants._nMaxFailedAccessAttempts;
                opts.Lockout.AllowedForNewUsers = true;
                opts.Password.RequireDigit = true;
                opts.Password.RequireLowercase = true;
                opts.Password.RequireUppercase = true;
                opts.Password.RequireNonAlphanumeric = true;
                opts.Password.RequiredLength = Heron.Library.Classes.Constants._nMinRequiredDigitsPassword;
            }).AddEntityFrameworkStores<Heron.Data.DB.Extensions.IdentityExtend.DbContext>().AddDefaultTokenProviders().AddUserManager<UserManager<Heron.Data.DB.Extensions.IdentityExtend.User>>();
            loServices.AddScoped<SignInManager<Heron.Data.DB.Extensions.IdentityExtend.User>>();
            loServices.AddScoped<UserManager<Heron.Data.DB.Extensions.IdentityExtend.User>>();
            loServices.AddScoped<RoleManager<Heron.Data.DB.Extensions.IdentityExtend.Role>>();
            loServices.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = new PathString("/Account/Index");
                options.Cookie.Name = "HeronAuthCookie";
                options.Cookie.HttpOnly = true;
            });
            loServices.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Index";
            });
            loServices.AddDistributedMemoryCache();
            loServices.AddMvcCore(options =>
            {
                options.RespectBrowserAcceptHeader = true;
            })
            .AddJsonFormatters();
            loServices
                .AddMvc(options =>
                {
                    options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddSessionStateTempDataProvider()
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            loServices.AddKendo();
            loServices.Configure<RecaptchaSettings>(this._oConfiguration.GetSection("RecaptchaSettings"));
            loServices.AddTransient<IRecaptchaService, RecaptchaService>();
            loServices.Configure<IISOptions>(this._oConfiguration);
            loServices.Configure<RequestLocalizationOptions>(options =>
            {
                options.RequestCultureProviders.Clear();
                options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-GB");
                options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-GB") };
            });
        }
        catch (Exception loException)
        {
            Heron.Library.Classes.Utility.MakeExceptionMessage(loException, "\r\n", "Startup.ConfigureServices");
        }
    }

    public void Configure(IApplicationBuilder loApp, IHostingEnvironment loEnv)
    {
        try
        {
            if (!this._bIsStaging)
            {
                loApp.UseHttpsRedirection();
            }
            using (var serviceScope = loApp.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {
                var loContext = serviceScope.ServiceProvider.GetService<Heron.Data.DB.HeronContext>();
                loContext.Database.EnsureCreated();
                loContext.Database.Migrate();
                var loContext2 = serviceScope.ServiceProvider.GetService<Heron.Data.DB.Extensions.IdentityExtend.DbContext>();
                loContext2.Database.EnsureCreated();
            }
            if (loEnv.IsDevelopment())
            {
                loApp.UseDeveloperExceptionPage();
            }
            else
            {
                loApp.UseExceptionHandler("/Shared/Error");
                loApp.UseHsts();
            }
            loApp.UseStatusCodePages(async context =>
            {
                context.HttpContext.Response.ContentType = "text/plain";
                await context.HttpContext.Response.WriteAsync("Status code page, status code: " + context.HttpContext.Response.StatusCode);
            });
            loApp.UseStaticFiles();
            loApp.UseSession();
            loApp.UseCookiePolicy();
            loApp.UseAuthentication();
            loApp.UseMvc(routes =>
            {
                routes.MapRoute(name: "dashboard", template: "{controller=Dashboard}/{action=Index}/{lsData?}");
                routes.MapRoute(name: "default", template: "{controller=Account}/{action=Index}/{lsMessage?}");
            });
            var supportedCultures = new[] { new CultureInfo("en-GB") };
            loApp.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture("en-GB"),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });
        }
        catch (Exception loException)
        {
            Heron.Library.Classes.Utility.MakeExceptionMessage(loException, "\r\n", "Startup.Configure");
        }
    }

Bad Gateway message after above line executes...


Solution

  • A solution to this has been found...

    https://forums.asp.net/p/2156143/6266248.aspx?p=True&t=636961808361687440

    See above thread.

    In essence it was a user claim value containing an image which exceeded the response header size.

    This might be a problem for core as a nice place to store an image (avatar) for an identity user is within userclaim.

    All for now.

    David

    Edit ...

    The code below should point you to the User Claim area in your code. I had to remove a User Claim containing an image (Profile Pic) which was too large for the area I was storing it in. So I moved it to another area in my DB.

            public class User : IdentityUser
        {
            public List<Claim> GetClaims()
            {
                try
                {
                    List<Claim> loClaims = new List<Claim>();
                    loClaims.Add(new     Claim("_nAuthenticationType",          this._nAuthenticationType.ToString(),  this._nAuthenticationType.GetType().ToString()));
                    loClaims.Add(new     Claim("_nGridToolbarPosition",         this._nGridToolbarPosition.ToString(), this._nGridToolbarPosition.GetType().ToString()));
                    loClaims.Add(new     Claim("_nMode",                        this._nMode.ToString(),                 this._nMode.GetType().ToString()));
                    loClaims.Add(new     Claim("_nCultureId",                   this._nCultureId.ToString(),            this._nCultureId.GetType().ToString()));
                    loClaims.Add(new     Claim("_bHideDashboard",               this._bHideDashboard.ToString(),        this._bHideDashboard.GetType().ToString()));
                    loClaims.Add(new     Claim("_nSalutation", this._nSalutation.ToString(), this._nSalutation.GetType().ToString()));
                    loClaims.Add(new     Claim("_nHOTPCounter", this._nHOTPCounter.ToString(), this._nHOTPCounter.GetType().ToString()));
                    if (!string.IsNullOrEmpty(this._sFirstName))
                    {
                        loClaims.Add(new Claim("_sFirstName",                   this._sFirstName.ToString(),            this._sFirstName.GetType().ToString()));
                    }
                    if (!string.IsNullOrEmpty(this._sMiddleName))
                    {
                        loClaims.Add(new Claim("_sMiddleName",                  this._sMiddleName.ToString(),           this._sMiddleName.GetType().ToString()));
                    }
    
                    loClaims.Add(new     Claim("_sLastName",                    this._sLastName.ToString(),             this._sLastName.GetType().ToString()));
                    if (!string.IsNullOrEmpty(this._sMobile))
                    {
                        loClaims.Add(new Claim("_sMobile",                      this._sMobile.ToString(),               this._sMobile.GetType().ToString()));
                    }