• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.netframeworkidentity学习笔记

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

关于 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 : 

            // 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);
            }
View Code

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);  
}
View Code

add roles

await userManager.AddToRoleAsync(user.Id, role);
View Code

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>");
View Code

confirm email 

var result = await UserManager.ConfirmEmailAsync(userId, code);
View 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>");
View Code

reset password by code 

          var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
View Code

get external loginInfo and sign in 

var loginInfo = await HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync();
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
View Code

add external login

result = await UserManager.AddLoginAsync(user.Id, info.Login);
View Code

sign out 

AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
View Code

redirect to login 

var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
View Code

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);
}
View Code

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);
View 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();
View Code

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);
View Code

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
[转]在ASP.NET中把图片保存到SQLSERVER数据库发布时间:2022-07-10
下一篇:
使用WebDevHelper辅助ASP.NETAJAX程序开发发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap