ASP.NET Identity不会对同一请求更新Identity信息

本文关键字:Identity 请求 更新 信息 NET ASP | 更新日期: 2023-09-27 18:12:07

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

按要求编写代码(AngularJS将AJAX post转换为WebAPI控制器登录方法)

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

ASP.NET Identity不会对同一请求更新Identity信息

直到下一个请求才会得到一个已签名的身份,因为对SignIn的调用是导致在响应上设置cookie的原因。该cookie将在后续请求中转换为标识,但现在更改当前请求的标识已经太晚了。

当使用Owin身份验证时,当cookie处理程序在Web API控制器之后处理请求时,AuthenticationManager.SignIn()方法几乎不发送消息给cookie处理程序来设置cookie(参见我的博客文章了解Owin外部身份验证管道的详细信息)。

但是,如果登录成功,则Login方法返回true,如果登录失败,则返回false,因此您可以在Login操作中使用该信息来发送回信息。如果您不仅想知道登录是否成功,还想知道实际的身份,您可以更改Login(),在登录成功时返回用户,如果登录失败则返回null

我登录用户并设置cookie;然而,当我在同一请求上检查用户的身份时,它显示为空白,IsAuthenticated为false。

这只是你缺乏关于ASP如何使用的知识。净管道工程。

发生的事件有相当大的管道。我很确定MVC在ProcessRequest方法中运行。这个方法在AuthenticateRequest事件和PostAuthenticateRequest事件之后。这意味着整个ASP。Net身份验证框架永远不能在ProcessRequest方法期间更新。这就是为什么你会看到几乎所有的系统都在之后进行重定向,以便下一个请求具有所有的身份验证(IIdentity, IPrincipal, IsAuthenticated等)。

我希望将用户是否在同一请求上登录发送回UI。这可能吗?

代码怎么可能不能呢?第一个请求要么对它们进行身份验证,要么不进行身份验证,无论代码做什么,都知道它们是否经过身份验证。

我希望将用户是否在同一请求上登录发送回UI。这可能吗?

是的。如其他回复所述,您可以。

我只是想涵盖的情况下,当你在相同的请求,但在上下文之外的SignIn发生。

通过Owin,您可以使用如下扩展方法:

    /// <summary>
    /// Check if the user was authenticated in the current request, or in a previous one
    /// </summary>
    public static bool IsUserAuthenticated(this IOwinContext context)
    {
        if (context.Request.User.Identity.IsAuthenticated)
            return true;
        if (null != context.Authentication.AuthenticationResponseGrant && null != context.Authentication.AuthenticationResponseGrant.Identity)
        {
            return context.Authentication.AuthenticationResponseGrant.Identity.IsAuthenticated;
        }
        return false;
    }