ASP.NET MVC Not logged in after successfully signe

2019-08-02 20:03发布

问题:

In my own machine and browser (chrome), I am not able to login in my website. It works in other browsers, with other users of chrome and in incognito window. It also works in my development environment or in other stages of the same website.

My relevant code regarding login is the following:

=> StartUp.ConfigureAuth

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, Data.DbContainer.Entities.User>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});            
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

=> Login endpoint

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    SignInStatus result;
    using (var mainDb = MainDbDataManager.GetInstance())
    {
        var user = await mainDb.UserManager.FindByNameAsync(model.Username);
        // Check if user has permission to access CMS
        if (user != null && !await mainDb.UserManager.IsInAnyRoleAsync(user.Id, Customer.RoleName, Administrator.RoleName))
        {
            result = SignInStatus.Failure;
        }
        else
        {
            using (var signInManager = HttpContext.GetOwinContext().Get<ApplicationSignInManager>())
            {
                result = await signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
            }
        }

        switch (result)
        {
            case SignInStatus.Success:
                {
                    // Set user's language
                    Session[Core.Helpers.ConstantsHelper.SessionConstants.LanguageCodeKey] = user.Language.Code;

                    return RedirectToLocal(returnUrl);
                }
            case SignInStatus.LockedOut:
                ModelState.AddModelError("", Strings.LoginDisabledError);
                return View(model);
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", Strings.LoginFailedError);
                return View(model);
        }
    }
}

I debugged the login endpoint and I noticed that the sign in is successful, but the User.Identity.Username is null, as long as Request.IsAuthenticated in my next endpoint is false.

I checked already this, but I could not find a successful solution.

I tried the following:

  • Adding Session["Workaround"] = 0; to Session_Start(), as mentioned in the previous link. I am not sure this is the correct place, but it seems so.
  • Applying SystemWebCookieManager, as mentioned in the previous link.
  • Removing the cookies of the browser
  • Restarting the browser
  • Calling AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);, even though there is no logged user.

I really do not know whether this is a browser problem or a development problem.

Could anyone find a solution or a workaround?

回答1:

As I told in the question, I removed the cookies of the browser (Chrome).

I did it through developer tools (Application > Cookies), but it seems this is not enough.

After I removed the cookies again through settings (Privacy > Content settings > All cookies and site data), the login worked properly.

More details about this action here: https://productforums.google.com/forum/#!topic/chrome/YEE24sDJxfo

Although I am not able to be sure about it, I wrote this as an answer (and will mark as correct) supposing it was a browser problem. If I find out that this occurs again to the same website due to no browser issues, I will uncheck this as the correct answer.