zoukankan      html  css  js  c++  java
  • 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 : 

                // 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
  • 相关阅读:
    Detect loop in a singly linked list
    Partition an array around an interger
    Binary search for the first element greater than target
    Searching in a rotated and sorted array
    where, group by, having
    [scalability] Find all documents that contain a list of words
    [DP] 堆盒子问题
    cocos2dx 内存管理的理解
    cocos2dx 2.x版本:简化提炼tolua++绑定自定义类到lua中使用
    OpenGl从零开始之坐标变换(下)
  • 原文地址:https://www.cnblogs.com/keatkeat/p/6025474.html
Copyright © 2011-2022 走看看