关于 cookie expiry & securityStamp
http://www.jamessturtevant.com/posts/ASPNET-Identity-Cookie-Authentication-Timeouts/ (blog 说的很不错)
http://*.com/questions/19487322/what-is-asp-net-identitys-iusersecuritystampstoretuser-interface
http://*.com/questions/28947342/asp-net-identity-securitystampvalidator-onvalidateidentity-regenerateidentity-pa
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(5),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
},
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromMinutes()
});
SlidingExpiration : 要不要自动更新 cookie, 如果 user 一直保持使用就不会过期.
ExpireTimeSpan : cookie 的有效时间咯
ValidateInterval : identity cookie 会保存 user 的 infomation, 但是 information 是会被 update 的, 比如 password 等等, 最极端的方法是每一个 request 都去检查最新的 user information 来做判断.
不过这样又很伤性能, 平衡方式是 set 一个比较短的时间内去检查, validateInterval 就是干这个的. 而如何检查这个用户资料更新了呢 ? identity 的检验方式是对比 securityStamp, 默认情况下当password
change and external login change 的时候会 update 这个 securityStamp, 我们也可以自己调用 UserManager.UpdateSecurityStamp(userId);
IsPersistent = true
http://*.com/questions/31946582/how-ispersistent-works-in-owin-cookie-authentication
通常是 true, 如果 false 表示这个 cookie 不作为固体保存, 只保存在 cache, browser 一关掉就消失.
常用 : 基本上看 vs2015 demo template 就很完整了
获取 manager :
HttpContext.GetOwinContext().Get<ApplicationSignInManager>() HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()
login by password :
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: 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);
}
create user and login by user
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
}
add roles
await userManager.AddToRoleAsync(user.Id, role);
email confirm code and sent
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
confirm email
var result = await UserManager.ConfirmEmailAsync(userId, code);
send reset password code
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
reset password by code
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
get external loginInfo and sign in
var loginInfo = await HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync();
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
add external login
result = await UserManager.AddLoginAsync(user.Id, info.Login);
sign out
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
redirect to login
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
generate phone token and send sms
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await UserManager.SmsService.SendAsync(message);
}
change password & change phone
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code);
get all allow external login
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
delete role and user
var userManager = context.Get<UserManager>();
await userManager.RemoveFromRoleAsync(staff.userId, "Staff");
var user = await userManager.FindByIdAsync(staff.userId);
await userManager.DeleteAsync(user);