question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

LogIn randomly stops working

See original GitHub issue

Hello and thanks for taking the time to read/assist with this issue. I’m hoping that someone will have a Eureka moment and be able to steer me in the right direction. I’ve spent 2 days searching blogs, technical docs, everything and no solution.

Issue: Login will fail after some random amount of time, as soon as 5 minutes and other times it’s taken 4hrs before users aren’t able to login anymore. Sometimes clearing browser cache/cookies will allow some users back in but not everyone. The only sure-fire way to allow people back into the application (hosted on IIS10/server 2016) is to recycle the dedicated application pool. There are no exceptions being thrown on the hosting server that I can chase… I can’t reproduce the issue locally (in debug), only on the deployed server. Looking through the event log there isn’t anything that directly correlates my “can’t login behavior” with an event. Turned on trace logging and nothing there as well. This issue has been plaguing me for a week now since I deployed the site for UAT. There is only 1 “warning” message capture throughout the past week… not sure if it even helps or should be chased…

Exception information: 
    Exception type: HttpException 
    Exception message: Server cannot append header after HTTP headers have been sent.
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
   at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
   at Microsoft.Owin.Infrastructure.ChunkingCookieManager.AppendResponseCookie(IOwinContext context, String key, String value, CookieOptions options)

Analyzing fiddler traffic I can tell that the users credentials succeed verification because there is a redirect from Login.aspx to Home.aspx. On Home load, I do an IsAuthenticated check which is checking for the cookie presence. I can tell that when my application is an error state (can’t login) that the cookie isn’t being generated. I can see the cookie being set correctly before this fails using browser debugging tools and fiddler. (also using friendly urls)

Failing scenario fiddler: No. Result Protocol Host URL Body Caching Content-Type Process Comments Custom 1 302 HTTP webdev01:8022 /Views/Account/Login 133 no-cache; Expires: -1 text/html; charset=utf-8 chrome:13744 2 200 HTTP Tunnel to clients1.google.com:443 0 chrome:13744 3 301 HTTP webdev01:8022 /Views/Home.aspx 128 text/html; charset=utf-8 chrome:13744 4 302 HTTP webdev01:8022 /Views/Home 142 private text/html; charset=utf-8 chrome:13744 5 301 HTTP webdev01:8022 /Views/Account/Login.aspx 137 text/html; charset=utf-8 chrome:13744 6 200 HTTP webdev01:8022 /Views/Account/Login 5,370 private text/html; charset=utf-8 chrome:13744

Login.aspx.cs

var result = signinManager.PasswordSignIn(UserNameTextBox.Text, UserPasswordTextBox.Text, false, shouldLockout: true); //(textboxes are regex protected)
switch (result)
{
    case SignInStatus.Success:
        SecurityManager.LogIn(UserNameTextBox.Text, Context.GetOwinContext());
        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);

SecurityManager.Login

        public static void LogIn(string username, IOwinContext context)
        {
            var claims = new List<Claim>() { new Claim(ClaimTypes.Name, username), new Claim("UserImpersonation", "false"), new Claim("OriginalUsername", username) }; //Creating a claim with the email address as the name of the identity.
            var claimIdentity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); 
            var owinContextMgr = context?.Authentication;
            owinContextMgr.SignIn(claimIdentity);
        }

The application allows “run as user” functionality but this error is without getting that far… and run as works just fine when the app isn’t in error state.

Master.cs

        protected void Logout(object sender, EventArgs e)
        {
            //Signout and Redirect. This removes the "PrincipalUser" cookie which stores the Identity information.
            var currentContext = HttpContext.Current.GetOwinContext();
            var authenticationManager = currentContext.Authentication;
            authenticationManager.SignOut();
            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }

Log out works fine with the application not being in error state. Able to log out and back in 10 times after a fresh application pool reset with no issues whatsoever… and as different users.

Startup.Auth.cs

    public partial class Startup {
        public void ConfigureAuth(IAppBuilder app)
        {
            var cookieTimeOut = Convert.ToDouble(ConfigurationManager.AppSettings["AuthCookieTimeOutMins"].ToString());
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(cookieTimeOut));
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                CookieName = "UserManagement",
                ExpireTimeSpan = TimeSpan.FromMinutes(cookieTimeOut),
                LoginPath = new Microsoft.Owin.PathString("~/Views/Account/Login.aspx")
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        }
    }

Background: I’m leveraging Owin.SignIn and Owin.SignOut to handle authentication in my webforms/c#/sql2016 app targeting 461. Since this is a public facing app and not internal, we don’t use AD. Instead we are authenticating/verifying user credentials against our database held hashed passwords.

Any assistance with this will be GREATLY appreciated… I’m starting to think I’ll have to use some other form of authentication handling here soon if I can’t get this resolved…

I will answer any questions expeditiously 😃

Thanks, Pablo-

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
liuyl1992commented, Jul 24, 2019

This is possible be very useful to me. Thank you

0reactions
pabblurcommented, Jun 26, 2018

@Tratcher I wanted to reach back out and thank you for your assistance. The documentation you provided was most insightful. Since I was already on v4 the solution for us was simple.

Reconfigure the CookieAuthenticationMiddleware to write directly to System.Web’s cookie collection. app.UseCookieAuthentication(new CookieAuthenticationOptions { // … CookieManager = new SystemWebCookieManager() });

Really appreciate your time and efforts!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why are my login and password suddenly not working (can ...
After starting up the computer, the initial screen asks for my log-in and password. I type it in and I get the "invalid...
Read more >
How to Fix Windows 10 Login Problems [EXPERT GUIDE]
Common Windows 10 login issues; Method 1: Restart your computer; Method 2: Run the Startup Repair tool; Method 3: Boot your computer in...
Read more >
How to Fix Problems During the Windows Login Process
A failed update or one-time startup process can sometimes cause stopping, freezing, or reboot-loop issues during the login process.
Read more >
I can't log in to a website
Having trouble logging into a website? There are lots of things that could be wrong. Here's a detailed guide to help you find...
Read more >
Unable to login with correct password, have to try multiple ...
Do you wait some period of time before attempting again? It's possible your failed login attempts locked your account. After waiting a few ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found