(使用ASP.NET 4.X 中的时候必定都用过Forms认证即FormsAuthentication作登陆用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cookie中。可是它很难进行扩展,更没法与第三方认证集成,所以,在 ASP.NET Core 中对认证与受权进行了全新的设计,并使用基于声明的认证(claims-based authentication))数组
@{ ViewData["Title"] = "Admin"; } <h2>@ViewData["Title"]</h2> <p>Admin Page</p>
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options=>{//自定义登录地址,不配置的话则默认为http://localhost:5000/Account/Login options.LoginPath="/Account/MyLogin"; });
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); //注意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的值。浏览器
public class AccountController : Controller { public IActionResult Index() { return View(); } //登录 public IActionResult MakeLogin() { var claims = new List<Claim>(){ new Claim(ClaimTypes.Name,"wangyuting"), new Claim(ClaimTypes.Role,"admin") }; //必需要加CookieAuthenticationDefaults.AuthenticationScheme,否则没法解析 var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return Ok(); } //登出 public IActionResult Logout() { HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); } }
在ASP.NET CORE中使用Cookie认证登陆用户的方法和传统的FormsAuthentication不太同样,大体步骤以下:cookie
因此咱们能够看到整个ASP.NET CORE的Cookie认证登陆流程比之前ASP.NET的FormsAuthentication仍是要复杂许多,毕竟之前一个FormsAuthentication.SetAuthCookie方法就搞定了。app
在本文的例子中咱们在项目中默认的HomeController中建立了一个Acion方法Login,来实现用户登陆的代码。固然这里咱们实现的是最简的Cookie登陆,下面代码中实际上还能够设置Cookie是否持久化、Cookie多久过时、存储登陆用户信息的Cookie的名字是什么等,咱们就不作过多介绍了,你们能够阅读本文最后推荐的两份官方文档了解更多。框架
/// <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,登陆用户Basync
3.读取登陆用户信息ui
那么用户登陆后怎么将登陆用户的信息(好比用户名)读取出来呢?咱们在HomeController的Index方法中演示了如何判断当前用户是否已经登陆,而且读出登陆用户的用户名,Index方法的代码以下所示:加密
/// <summary> /// 该Action判断用户是否已经登陆,若是已经登陆,那么读取登陆用户的用户名 /// </summary> public IActionResult Index() { //若是HttpContext.User.Identity.IsAuthenticated为true, //或者HttpContext.User.Claims.Count()大于0表示用户已经登陆 if (HttpContext.User.Identity.IsAuthenticated) { //这里经过 HttpContext.User.Claims 能够将咱们在Login这个Action中存储到cookie中的全部 //claims键值对都读出来,好比咱们刚才定义的UserName的值Wangdacui就在这里读取出来了 var userName = HttpContext.User.Claims.First().Value; } return View(); }
注意,最好仍是用HttpContext.User.Identity.IsAuthenticated来判断用户是否已经登陆spa
注销用户设计
那么登陆用户后怎么注销登陆呢?咱们在HomeController的Logout方法中演示了如何注销登陆的用户,代码以下所示:
/// <summary> /// 该Action从Asp.Net Core中注销登陆的用户 /// </summary> public IActionResult Logout() { Task.Run(async () => { //注销登陆的用户,至关于ASP.NET中的FormsAuthentication.SignOut await HttpContext.SignOutAsync(); }).Wait(); return View(); }
果当前Http请求原本就没有登陆用户,那么调用HttpContext.SignOutAsync方法时也不会报错