【问题标题】:What set's the User.Identity.Name and User.Identity.IsAuthenticated?什么是 User.Identity.Name 和 User.Identity.IsAuthenticated?
【发布时间】:2015-08-22 12:38:57
【问题描述】:

我想知道用户身份名称是什么集合并将isAuthenticated更改为true。

为什么User.Identity.Name 是一个空字符串,而User.Identity.IsAuthenticated falseSignInManager.PasswordSignInAsync 返回了Success 之后。

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

    var userIdentityNameTest = User.Identity.Name; // Empty string

    var result = await SignInManager.PasswordSignInAsync(
                                             model.Email, model.Password, 
                                             model.RememberMe, shouldLockout: false);
    // result is "Success"

    userIdentityNameTest = User.Identity.Name;
    // userIdentityNameTest is still an empty string?
    // User.Identity.IsAuthenticated is still 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);
    }
}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-identity iprincipal iidentity


    【解决方案1】:

    似乎SignInManager.PasswordSignInAsync 仅验证输入的数据并在您不使用TwoFactorAuthentication 时运行AuthenticationManager.SignInAuthenticationManager.SignIn 在这种情况下只设置身份验证 cookie 来响应。

    因此,User.Identity 可在对您的应用程序的后续请求中使用。要通过Name 获取ApplicationUser,您可以使用ApplicationUserManager,如下所示:

    UserManager.FindByNameAsync(model.Name)

    【讨论】:

    • 在执行“SignInManager.PasswordSignInAsync”后,如何获取或设置登录用户的名称为“User.Identity”或“HttpContext.User”?