ASP.NET Identity 2.1 MVC方式
- 相关代码
-
注册创建用户并登陆
[HttpPost]
[ValidateAntiForgeryToken]
public async TaskRegister(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}// If we got this far, something failed, redisplay form
return View(model);
}private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}- Asp.Net Identity 和 OWIN Cookies Authentication 都是基于声明的系统。
- Asp.Net Identity 框架需要为用户生成一个ClaimsIdentity(用户拥有的所有声明,比如用户属于什么角色);
CreateIdentityAsync方法会生成一个ClaimsIdentity - 在这个步骤中,你可以在为新建用户添加更多的声明
- 通过OWIN中的AuthenticationManager调用SignIn,传入ClaimsIdentity。该方法将使用户登陆并生成一个Cookies,类似于FormsAuthentication.SetAuthCookie
- AuthenticationManager调用SignOut,类似FormsAuthentication.SignOut
-

浙公网安备 33010602011771号