Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Identity doesn't update Identity information on same request

I am working on a single page application using AngularJS and ASP.NET Identity 2. I log the user in and the cookie is set; however, when I check the Identity of the user on the same request, it shows it as blank and IsAuthenticated is false. However, these are populated on subsequent requests. I was hoping to send back to the UI whether or not the user was logged in on the same request. Is this possible?

Code as requested (AngularJS makes AJAX post into WebAPI controller Login method)

[HttpPost]
[AllowAnonymous]
[Route("Login")]
public async Task<IHttpActionResult> Login(LoginModel loginModel)
{
    var result = await _securityService.Login(loginModel.UserName, loginModel.Password);
    if (!result)
    {
        ModelState.AddModelError("errorMessage", "Invalid username or password.");
        return BadRequest(ModelState);
    }
    return Ok();
}

public async Task<bool> Login(string userName, string password, bool persistCookie = false)
{
    var user = await _userManager.FindAsync(userName, password);
    if (user != null)
        await SignInAsync(user, persistCookie);
    else
        return false;

    return true;
}

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    _authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    _authenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = isPersistent}, await CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));
}

public Task<ClaimsIdentity> CreateIdentity(ApplicationUser user, string authenticationType)
{
    return _userManager.CreateIdentityAsync(user, authenticationType);
}
like image 990
Todd Avatar asked Jul 09 '14 18:07

Todd


Video Answer


2 Answers

You won't get a signed in identity until the next request because the call to SignIn is what's causing a cookie to be set on the response. That cookie will turn into the identity on subsequent requests, but its too late to change your current request's identity.

like image 117
Hao Kung Avatar answered Oct 30 '22 17:10

Hao Kung


When using Owin authentication, the AuthenticationManager.SignIn() method barely sends a message to the cookie handler to set a cookie when the cookie handler gets to handle the request after the Web API Controller (see my blog post Understanding the Owin External Authentication Pipeline for details).

But the Login method returns true if the login was successful and false if not, so you can use that information in the Login action to send back information. If you don't only want to know if the login succeeded or not, but also want the actual identity you can change Login() to return the user in case of successful login and null if failed.

like image 31
Anders Abel Avatar answered Oct 30 '22 16:10

Anders Abel