故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

Net Core中使用cookie

8801人阅读 2019/1/9 22:44 总访问:3839917 评论:7 收藏:0 手机
分类: .NET Core

net core中可以使用传统的cookie也可以使用加密的cookie


NET CORE中使用传统cookie


设置:  

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

获取:

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

删除

 HttpContext.Response.Cookies.Delete("password");

 


传统的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");
            }
 
        }
    }






欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价