Startup.cs文件:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Home/Login"; options.ExpireTimeSpan = TimeSpan.FromDays(2); });
//注意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?}"); });
登录:
[HttpPost] public async Task<IActionResult> Login(LoginModel dto) { //登陆授权 if (dto.UserName == "admin" && dto.Password == "123456") { var claims = new List<Claim>(){ new Claim(ClaimTypes.Name,dto.UserName), new Claim(ClaimTypes.Role,"admin") }; var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity)); //验证是否授权成功 //if (User.Identity.IsAuthenticated) //{ // return RedirectToPage("Index"); //} return RedirectToAction("Applet", "Pages"); } else { ViewBag.msg = "账号密码错误"; return View(); } } public async Task<IActionResult> Logout() { //TODO:注销处理 await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction("Login"); }
特性:
需要认证:[Authorize]
忽略认证:[AllowAnonymous]