.NET Core中基于Cookie的认证

.net core中的权限认证比起.net mvc有一定的差异,为方便以后的工作和学习,今天就总结一篇.net core中基于cookie的认证。希望也能帮助到大家

一.配置相应的信息  

  1.先在ConfigureServices中注册Cookie认证服务

  

 public void ConfigureServices(IServiceCollection services)
        {   
        //注册身份认证服务        
       services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
            AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.LoginPath = new PathString("/Login/Index");  //指定未登录时跳转的页面
            });
            //注册身份授权服务
            services.AddAuthorization(options => {
                options.AddPolicy("test",builder=>
                {
                    builder.RequireClaim("FullName","job");  //配置相应的策略
                });
            });

        }

  2.在Configure中注册Cookie认证的中间件

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();     //这里要注意中间件的位置不能随意颠倒

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

二. 创建身份认证Cookie

      [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginAsync(string phone,string pwd)
        {
      //声明Claim存储用户的相关信息。标注用户的身份.这里的配置可以跟
         var claims = new List<Claim>
      {
          new Claim(ClaimTypes.Name, user.Email),
          new Claim("FullName","job"),           //这里填充的信息可以跟注册授权中的策略相对应,通过判定 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme,Policy = "test")] 确定是否授权 
          new Claim(ClaimTypes.Role, "Administrator"),
      };
    //通过Claim来创建ClaimsIdentity 类似于通过用户的身份来创建身份证
      var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
          ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);  //将创建的claimsIdentity传入到ClaimsPrincipal中
                    /*
                      Cookie设置
                     */
                    var properties = new AuthenticationProperties
                    {
                        // 持久保存
                        IsPersistent = true,
                        // 指定过期时间
                        //ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),
                        ExpiresUtc = DateTime.Now.AddDays(1)

                    };
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, properties);   //相当于.NET MVC中的FormsAuthentication.SetAuthCookie
                return Json(new { success = true, message = "" });
     }

三.获取登录用户的相关信息

 if (HttpContext.User.Identity.IsAuthenticated)  //判断用户是否通过认证
    {
        var userName = HttpContext.User.Claims.First().Value;
    }

四.注销用户

       public async Task<IActionResult> LogOut()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);  //类似于.NET MVC中FormsAuthentication.SignOut();
            return RedirectToAction("Index","Home");
        }

总结

  services.AddAuthentication()和 services.AddAuthorization()这两个服务,看似很相近,其实里面大有文章,一个是配置认证的信息,一个是配置授权的信息。AddAuthentication只是判断一下用户是谁,而AddAuthorization这个服务是判断用户有什么样的权限才能访问受保护的资源

 

上一篇:重新整理 .net core 实践篇————cookie 安全问题[三十八]


下一篇:使用cookie来做身份认证