.net core 3.0 Cookie认证

Startup.cs中的配置

  • ConfigureServices中注册Cookie认证服务(一行代码)
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //注册Cookie认证服务
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
        }
  • Configure方法中使用认证中间件(一行代码)
//使用认证中间件
            app.UseAuthentication();
            app.UseAuthorization();

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

登陆与验证

  • 登陆
var claims = new[] { new Claim("UserName", "Wangdacui") };
            var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity);
            Task.Run(async () =>
            {
                //登陆用户,至关于ASP.NET中的FormsAuthentication.SetAuthCookie
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

                //能够使用HttpContext.SignInAsync方法的重载来定义持久化cookie存储用户认证信息,例以下面的代码就定义了用户登陆后60分钟内cookie都会保留在客户端计算机硬盘上,
                //即使用户关闭了浏览器,60分钟内再次访问站点仍然是处于登陆状态,除非调用Logout方法注销登陆。
                //注意其中的AllowRefresh属性,若是AllowRefresh为true,表示若是用户登陆后在超过50%的ExpiresUtc时间间隔内又访问了站点,就延长用户的登陆时间(其实就是延长cookie在客户端计算机硬盘上的保留时间),
                //例如本例中咱们下面设置了ExpiresUtc属性为60分钟后,那么当用户登陆后在大于30分钟且小于60分钟内访问了站点,那么就将用户登陆状态再延长到当前时间后的60分钟。可是用户在登陆后的30分钟内访问站点是不会延长登陆时间的,
                //由于ASP.NET Core有个硬性要求,是用户在超过50%的ExpiresUtc时间间隔内又访问了站点,才延长用户的登陆时间。
                //若是AllowRefresh为false,表示用户登陆后60分钟内无论有没有访问站点,只要60分钟到了,立马就处于非登陆状态(不延长cookie在客户端计算机硬盘上的保留时间,60分钟到了客户端计算机就自动删除cookie)
                /*
                await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                user, new AuthenticationProperties()
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60),
                    AllowRefresh = true
                });
                */

            }).Wait();
  • 判断是否登陆,并取登陆信息
if (HttpContext.User.Identity.IsAuthenticated)
            {
                //这里经过 HttpContext.User.Claims 能够将咱们在Login这个Action中存储到cookie中的全部
                //claims键值对都读出来,好比咱们刚才定义的UserName的值Wangdacui就在这里读取出来了
                ViewBag.UserName = HttpContext.User.Claims.First().Value;
            }

以上亲测可用html

负载均衡

警告: ASP.NET Core使用 ASP.NET Core data protection stack 来实现Cookie身份认证。若是在服务器集群中必须配置 ASP.NET Core Data Protection,有关详细信息,请参阅 Configuring data protection。若是你的ASP.NET Core站点使用了负载均衡部署了多个实例,就要作ASP.NET Core Data Protection的配置,不然ASP.NET CORE跨多个实例进行Cookie身份认证会失败。web

还能够参考:Host ASP.NET Core in a web farm 以及 Share authentication cookies among ASP.NET apps浏览器

如何管理ASP.NET Core Data Protection的过时key,能够查看:Data Protection - how to manage expired key?服务器

前面说了实际上在ASP.NET CORE的Cookie认证中还能够设置Cookie的名字、是否持久化存储等,能够参考以下两篇官方文档了解:cookie

Using Cookie Authentication without ASP.NET Core Identityapp

Cutting Edge - Cookies, Claims and Authentication in ASP.NET Core负载均衡

原文地址: https://www.cnblogs.com/OpenCoder/p/8341843.htmlasync

相关文章
相关标签/搜索