【问题标题】:ASP.NET Identity doesn't update Identity information on same requestASP.NET 身份不会在同一请求上更新身份信息
【发布时间】:2014-07-09 18:14:25
【问题描述】:

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

按要求编写代码(AngularJS 将 AJAX 发布到 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);
}

【问题讨论】:

  • 代码会很有帮助。
  • 代码已添加,希望对您有所帮助!顺便说一句,我虽然设置 AuthenticationMode.Active 可能会以某种形式有所帮助,但这没有任何帮助!
  • 所以如果我理解这一权利,除非请求包含 cookie(或令牌),否则身份信息将为空白。但我希望这是由身份验证管理器在登录时设置的?也许这是不可能的?
  • 你说的似乎是真的,但是用例是什么,为什么要在认证后直接检查认证?
  • 因为我认为它需要请求中的 cookie 来判断用户是否经过身份验证?并且由于该请求最初是匿名的,因此直到下一个请求才会接收它?我想发回确认信息,但我想 200 OK 就足够了?

标签: c# asp.net asp.net-identity owin claims-based-identity


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用 Owin 身份验证时,当 cookie 处理程序在 Web API 控制器之后处理请求时,AuthenticationManager.SignIn() 方法几乎不会向 cookie 处理程序发送消息以设置 cookie(有关详细信息,请参阅我的博客文章 Understanding the Owin External Authentication Pipeline) .

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

    【讨论】:

      【解决方案3】:

      我登录了用户并设置了cookie;但是,当我在同一请求中检查用户的身份时,它显示为空白并且 IsAuthenticated 为假。

      This is just a lack of knowledge on your part about how the ASP.Net pipeline works.

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

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

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

      【讨论】:

      • 重定向的原因完全不同。例如因为登录页面仅用作登录页面或者因为他们希望避免在 F5 上重新提交数据
      • 我可能确实缺乏知识,而且我没有使用 MVC (WebAPI),所以我之前在评论中所说的是正确的。感谢您的参考。不知道你的意思是代码怎么能不呢?是的,用户已通过身份验证,但如前所述,cookie 仍会在该响应中设置,因此后续请求应标识为已通过身份验证。
      【解决方案4】:

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

      是的。正如其他回复中所说,您可以。

      我只想介绍当您在同一个请求中但在登录发生的上下文之外的情况。

      通过 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;
          }
      

      【讨论】:

        猜你喜欢
        • 2014-02-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        • 2022-01-15
        • 2020-08-16
        • 2011-11-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多