How to get IsPersistent session in ASP.NET MVC?

I have an ASP.NET MVC 5.0 project using ASP.NET Identity. When a user logs in, I use this function to track the user through the system.

SignInManager.SignIn(user,IsPersistent,false)

In the user profile, I have the opportunity to change UserName, after which I need to automatically reassign the user to track the user. I log out and use this function to log in, but where can I get the property of the IsPersistentcurrent session?

I can store IsPersistent in the User table in the database after each login, but I think this is not the best solution.

+4
source share
2

LoginController, . ASP.NET Identity.

, , , . , , .

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

    SignInStatus result = SignInStatus.Failure;

    var user = UserManager.FindByEmail(model.Email);
    if (user != null)
    {
        var isPasswordOk = UserManager.CheckPassword(user, model.Password);
        if (isPasswordOk)
        {
            user.Claims.Add(new IdentityUserClaim() { ClaimType = "IsPersistent", ClaimValue = model.RememberMe.ToString() });
            await SignInManager.SignInAsync(user, model.RememberMe, false);

            result = SignInStatus.Success;
        }
    }

    // This doesn't count login failures towards account lockout
    // To enable password failures to trigger account lockout, change to shouldLockout: true
    //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);

        case SignInStatus.LockedOut:
            return View("Lockout");

        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });

        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

, , , .

if (User.Identity.IsAuthenticated)
{
    Claim claim = ((ClaimsIdentity)User.Identity).FindFirst("IsPersistent");
    bool IsPersistent = claim != null ? Convert.ToBoolean(claim.Value) : false;
}

, .

+1

IsPersistent, AuthenticateAsync:

@using Microsoft.AspNet.Identity;

var authenticateResult = await HttpContext.GetOwinContext()
                               .Authentication.AuthenticateAsync(
                                   DefaultAuthenticationTypes.ApplicationCookie
                               );
var isPersistent = authenticateResult.Properties.IsPersistent; //// true or false
0

Source: https://habr.com/ru/post/1659401/


All Articles