当前位置:首页 > Web开发 > 正文

"Wangdacui") };var claimsIdentity = new ClaimsIdentity(clai

2024-03-31 Web开发

大家在使用ASP.NET的时候必然都用过FormsAuthentication做登录用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cookie中。

此刻到了ASP.NET CORE的时代,但是ASP.NET CORE中没有FormsAuthentication这个对象,那么怎么做身份认证呢?答案是ASP.NET CORE已经为我们内置了Cookie身份认证的成果,而且使用起来非常便利,注意本文是基于ASP.NET CORE 2.0版原来论述Cookie认证方法的。

1.从ASP.NET CORE OWIN框架中启用Cookie身份认证成果

要在ASP.NET CORE中使用Cookie身份认证,第一步就是在项目中的OWIN框架文件Startup.cs中启用Cookie身份认证中间件。

首先我们在Startup中的ConfigureServices要领中使用services.AddAuthentication注册Cookie认证处事,如下代码所示:

public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //注册Cookie认证处事 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); }

然后在Startup中的Configure要领中使用app.UseAuthentication启用Cookie认证中间件(注意此中app.UseAuthentication和app.UseMvc的挪用挨次不能反),如下代码所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //注意app.UseAuthentication要领必然要放不才面的app.UseMvc要领前面,否者后面就算挪用HttpContext.SignInAsync进行用户登录后,使用 //HttpContext.User还是会显示用户没有登录,并且HttpContext.User.Claims读取不到登录用户的任何信息。 //这说明Asp.Net OWIN框架中MiddleWare的挪用挨次会对系统成果孕育产生很大的影响,各个MiddleWare的挪用挨次必然不能反 app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

这里趁便说一下app.UseAuthentication是用来干什么的,app.UseAuthentication会启用Authentication中间件,该中间件会按照当前Http请求中的Cookie信息来设置HttpContext.User属性(后面会用到),所以只有在app.UseAuthentication要领之后注册的中间件才华够从HttpContext.User中读取到值,这也是为什么上面强调app.UseAuthentication要领必然要放不才面的app.UseMvc要领前面,因为只有这样ASP.NET Core的MVC中间件中才华读取到HttpContext.User的值。

ASP.NET Core 3.0

由于在ASP.NET Core 3.0中,app.UseMvcapp.UseRoutingapp.UseEndpoints替代,所以app.UseAuthenticationapp.UseAuthorization,要放在app.UseRoutingapp.UseCors之后,并且在app.UseEndpoints之前,如下所示:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }

详情可以检察:Migrate from ASP.NET Core 2.2 to 3.0

2.登录用户

在ASP.NET CORE中使用Cookie认证登录用户的要领和传统的FormsAuthentication不太一样,大抵法式如下:

创建Claim类型的数组,将登录用户的所有信息(好比用户名)存储在Claim类型的字符串键值对中

将上面创建的Claim类型的数组传入ClaimsIdentity中,用来结构一个ClaimsIdentity东西

将上面创建的ClaimsIdentity东西传入ClaimsPrincipal中,用来结构一个ClaimsPrincipal东西

挪用HttpContext.SignInAsync要领,传入上面创建的ClaimsPrincipal东西,完成用户登录

所以我们可以看到整个ASP.NET CORE的Cookie认证登录流程比以前ASP.NET的FormsAuthentication还是要庞大许多,终究以前一个FormsAuthentication.SetAuthCookie要领就搞定了。

在本文的例子中我们在项目中默认的HomeController中创建了一个Acion要领Login,来实现用户登录的代码。固然这里我们实现的是最简的Cookie登录,下面代码中实际上还可以设置Cookie是否长期化、Cookie多久过期、存储登录用户信息的Cookie的名字是什么等,我们就不做过多介绍了,大家可以阅读本文最后保举的两份官方文档了解更多。

Login要领的代码如下:

/// <summary> /// 该Action登录用户Wangdacui到Asp.Net Core /// </summary> public IActionResult Login() { //下面的变量claims是Claim类型的数组,Claim是string类型的键值对,所以claims数组中可以存储任意个和用户有关的信息, //不过要注意这些信息都是加密后存储在客户端浏览器cookie中的,所以最好不要存储太多出格敏感的信息,,这里我们只存储了用户名到claims数组, //暗示当前登录的用户是谁 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(); return View(); }

如果当前Http请求原来登录了用户A,此刻挪用HttpContext.SignInAsync要领登录用户B,那么相当于注销用户A,登录用户B

3.读取登录用户信息

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30190.html