一、登陆页面的Controller
[Authorize(Roles = "Admin,SuperAdmin")] public class ManageController : Controller { public IActionResult Index() { return View(); } [AllowAnonymous] public IActionResult Login(string returnUrl = null) { _logger.LogInformation("进入登录页面"); TempData["returnUrl"] = returnUrl; ViewBag.Msg = " "; return View(); } [AllowAnonymous] [HttpPost] public async Task<IActionResult> LoginCheck(string name, string password, string returnUrl) { string loginName = Filter.FilterHTML(name); var account = await _context.Account.FirstOrDefaultAsync(g => g.LoginName.Equals(loginName)); if (account == null || (!account.Password.Equals(password))) { ViewBag.Msg = "账号或密码有误,请重新输入"; return View("Index"); } else { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Sid, account.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, account.Name)); identity.AddClaim(new Claim(ClaimTypes.Role, account.Role)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.Now.AddDays(1) }); if (returnUrl == null) { returnUrl = TempData["returnUrl"]?.ToString(); } if (returnUrl != null) { return LocalRedirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Manage"); } } } [HttpGet] public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction("login"); } [AllowAnonymous] public IActionResult Denied() { return View(); } }
二、配置Startup.cs的ConfigureServices方法,增加如下代码
//配置使用Authorize登陆认证 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = new PathString("/manage/login"); options.AccessDeniedPath = new PathString("/manage/denied"); });
三、配置Startup.cs的Configure方法,增加如下代码
app.UseAuthentication();//配置使用Authorize登陆认证