【发布时间】: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