net core使用加密cookie



        NET CORE中使用传统的cookie

          

         设置:        

 HttpContext.Response.Cookies.Append("password","123456");
          

         获取:     

    string value = "";
            HttpContext.Request.Cookies.TryGetValue("password", out value);


      Cookie是用的明文传递的:


       




    NET CORE中使用加密cookie


           1:使用nuget命令下载依赖            

                 Install-PackageMicrosoft.AspNetCore.Authentication.Cookies             

          注:添加过后重新生成一下,不然没有提示,强制写出来也会提示报错

         


           2:在startup.cs中注册   

     app.UseCookieAuthentication(new CookieAuthenticationOptions() {

                AuthenticationScheme="myuser", //名称
                AutomaticAuthenticate=true,//自动验证
                LoginPath= "/account/login"//登录地址
            });


          3:创建验证登录方法(写入cookie)             

 public async Task<IActionResult> ExeLogin()
        {

            int userid = 1;
            string username = "xp";

            ClaimsIdentity identity = new ClaimsIdentity("Forms");
            identity.AddClaim(new Claim(ClaimTypes.Sid, userid.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Name, username));
            identity.AddClaim(new Claim("password", "123456"));//自己随便写一个名字

            var principal = new ClaimsPrincipal(identity);
            await HttpContext.Authentication.SignInAsync("myuser", principal, new AuthenticationProperties { IsPersistent = true });

            //登录后需要返回的页面
            //string returnUrl = Request.Query["returnUrl"];
            //if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);

            return RedirectToAction("index", "account");
        }

      

         4:获取加密cookie的方法               

 [Authorize(ActiveAuthenticationSchemes = "myuser")]
        public IActionResult Index()
        {
            //用户用户信息
            var userId = User.FindFirst(ClaimTypes.Sid).Value;
            var userName = User.Identity.Name;

            //获取用户名方法2
            string username2 = User.FindFirst(ClaimTypes.Name).Value;
            //获取名字叫password的值
            string password = User.FindFirst("password").Value;


            ViewBag.userId = userId;
            ViewBag.username = username2;

            return View();
        }

         注:使用如下特性可以在用户没有登录得时候请求登录方法(Controller与action都适用)

               [Authorize(ActiveAuthenticationSchemes="myuser")]



         5:退出登录方法(删除cookie)       

   public async Task<IActionResult> Exit()
        {
            await HttpContext.Authentication.SignOutAsync("myuser");   // Startup.cs中配置的验证方案名

            return RedirectToAction("index", "home");
        }

          可以看到cookie是加密后的

     

         

      NET CORE中配合控制器使用加密cookie

                 

             在过滤器中限制除了登录本身都需要登录后才能访问

              

    public class IsLoginFilter:ActionFilterAttribute
    {     
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string controller = context.RouteData.Values["controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();

            if (controller.ToLower() == "account")//忽略登录本身
                return;


            //检查是否登录
            var  sid = context.HttpContext.User.FindFirst(ClaimTypes.Sid);

            //表示用户没有登录跳转到登录页
            if (sid == null)
            {
                context.Result = new RedirectResult("/account/login");
            }

        }
    }

       

     




   



猜你喜欢

转载自blog.csdn.net/aojiancc2/article/details/74075092