1、在Startup類的Configure方法,添加身份驗證的中間件AuthenticationMiddleware 2、在Startup類的ConfigureServices方法,添加Cookie驗證的服務,使用Cookies驗證體系, CookieAuthenticationDefaults.A ...
1、在Startup類的Configure方法,添加身份驗證的中間件AuthenticationMiddleware
app.UseAuthentication();
2、在Startup類的ConfigureServices方法,添加Cookie驗證的服務,使用Cookies驗證體系,
CookieAuthenticationDefaults.AuthenticationScheme="Cookies"
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.AccessDeniedPath = "/Sys/Home/Index"; options.LoginPath = "/Sys/Home/Login"; options.Cookie.Name = "AuthCookie"; options.Cookie.Path = "/"; options.Cookie.Expiration = TimeSpan.FromMinutes(30); });
3、添加登錄action,ClaimsIdentity(string authenticationType)的authenticationType必須和service設置的驗證體系一樣,才能正常驗證,
[HttpPost] [AllowAnonymous] public async Task<ActionResult> Login() { string AdminAccount = Request.Form["AdminAccount"]; string Password = Request.Form["Password"]; if (string.IsNullOrWhiteSpace(AdminAccount)) { return JsonError("賬號不能為空"); } if (string.IsNullOrWhiteSpace(Password)) { return JsonError("密碼不能為空"); } Admin admin = _context.Admins.FirstOrDefault(c => c.AdminAccount == AdminAccount && c.Password == Password); if (admin == null) { return JsonError("用戶名或者密碼錯誤"); } ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Name, admin.Id.ToString())); await HttpContext.SignInAsync(new ClaimsPrincipal(identity)); return JsonSuccess(); }
4、在需要驗證的控制器上加[AuthorizeAttribute]特性,通過HttpContext.User.Identity.IsAuthenticated可判斷用戶是否已通過驗證
5、退出登錄Action
/// <summary> /// 退出登錄 /// </summary> /// <returns></returns> public async Task<ActionResult> SignOut() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return JsonSuccess(); }