ASP.NET Identity不会在同一请求上更新Identity信息 [英] ASP.NET Identity doesn't update Identity information on same request

查看:118
本文介绍了ASP.NET Identity不会在同一请求上更新Identity信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AngularJS和ASP.NET Identity 2开发单页应用程序.我登录用户并设置了cookie.但是,当我在同一请求上检查用户的身份时,它显示为空白,而IsAuthenticated为false.但是,这些是在后续请求中填充的.我希望无论用户是否在同一请求上登录,都将发送回UI.这可能吗?

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?

请求的代码(AngularJS将AJAX发布到WebAPI控制器的Login方法中)

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);
}

推荐答案

在下一个请求之前,您将无法获得登录身份,因为对SignIn的调用是导致在响应上设置Cookie的原因.该Cookie将在后续请求中转变为身份,但为时已晚,无法更改您当前请求的身份.

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.

这篇关于ASP.NET Identity不会在同一请求上更新Identity信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆