asp.net framework identity 学习笔记
关于 cookie expiry & securityStamp
http://www.jamessturtevant.com/posts/ASPNET-Identity-Cookie-Authentication-Timeouts/ (blog 说的很不错)
http://stackoverflow.com/questions/19487322/what-is-asp-net-identitys-iusersecuritystampstoretuser-interface
http://stackoverflow.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(30) });
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://stackoverflow.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 :
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// 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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); }
add roles
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
await userManager.AddToRoleAsync(user.Id, role);
email confirm code and sent
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var result = await UserManager.ConfirmEmailAsync(userId, code);
send reset password code
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
get external loginInfo and sign in
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var loginInfo = await HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync(); var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
add external login
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
result = await UserManager.AddLoginAsync(user.Id, info.Login);
sign out
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
redirect to login
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
generate phone token and send sms
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var userManager = context.Get<UserManager>(); await userManager.RemoveFromRoleAsync(staff.userId, "Staff"); var user = await userManager.FindByIdAsync(staff.userId); await userManager.DeleteAsync(user);
相关文章
- ASP.NET MVC之表单集合数据自动绑定到对象属性(集合)中
- Asp.net mvc 网站之速度优化 -- 页面缓存
- 学习ASP.NET Core Blazor编程系列十五——查询
- 学习ASP.NET Core Blazor编程系列三十——JWT登录(4)
- 学习ASP.NET Core Blazor编程系列二十九——JWT登录(3)
- HTTP Error 500.31 - Failed to load ASP.NET Core runtime
- .NET Generic Host in ASP.NET Core
- Quickstart: Create and publish a NuGet package using Visual Studio (.NET Standard, Windows only)
- Asp.Net Mvc jQuery Unobtrusive Validation input tag必须是在form里面
- ASP.NET postback with JavaScript (UseSubmitBehavior)
- 简述C#中IO的应用 RabbitMQ安装笔记 一次线上问题引发的对于C#中相等判断的思考 ef和mysql使用(一) ASP.NET/MVC/Core的HTTP请求流程
- Asp.Net Core 轻松学-一行代码搞定文件上传 JSONHelper
- bootstrap-data-target触发模态弹出窗元素的data使用 data-toggle与data-target的作用 深入ASP.NET MVC之九:Ajax支持 Asp.Net MVC4系列--进阶篇之AJAX
- sql server 关于表中只增标识问题 C# 实现自动化打开和关闭可执行文件(或 关闭停止与系统交互的可执行文件) ajaxfileupload插件上传图片功能,用MVC和aspx做后台各写了一个案例 将小写阿拉伯数字转换成大写的汉字, C# WinForm 中英文实现, 国际化实现的简单方法 ASP.NET Core 2 学习笔记(六)ASP.NET Core 2 学习笔记(三)
- C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题
- Aspose.Words for .NET查找和替换教程——使用元字符查找和替换文本
- Asp.net中的【request】的两种取值方式(笔记)
- State Management in ASP.NET - Introduction
- ASP.NET Core Web API下事件驱动型架构的实现(五):在微服务中使用自我监听模式保证数据库更新与消息派发的可靠性
- 七天学会ASP.NET MVC (一)——深入理解ASP.NET MVC
- C#/Asp.Net 获取各种Url的方法
- ASP.NET Core 折腾笔记二:自己写个完整的Cache缓存类来支持.NET Core
- asp.net Core依赖注入汇总
- asp.net中 使用参数化mysqlparameter 保存数据时,总保存成一个汉字的解决方案。
- Asp.net web form 动态生成控件的注意事项
- ASP.Net WebForm温故知新学习笔记:一、aspx与服务器控件探秘