Startup:
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); //添加 Cookie 认证信息 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "TestCookie"; options.LoginPath = new PathString("/Account/Login"); options.AccessDeniedPath = new PathString("/Account/Denied"); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
登录代码:
[HttpPost] public async Task<IActionResult> LoginAsync([FromBody] dynamic loginInfo) { var userList = new List<dynamic> { new { LoginId = "1", UserName = "1Name", Password = "2", Role = "admin" }, new { LoginId = "2", UserName = "2Name", Password = "2", Role = "system" } }; string loginId = loginInfo.LoginId; string password = loginInfo.Password; var user = userList.FirstOrDefault(s => s.LoginId == loginId && s.Password == password); if (user != null) { //用户标识 var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Sid, user.LoginId)); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity) //, new AuthenticationProperties() { IsPersistent = true } , ExpiresUtc = DateTime.UtcNow.AddDays(1) } ); return Json(new { result = "OK" }); } else { return Json(new { result = "Error" }); } }
Home/Index:
public class HomeController : Controller { [Authorize] public IActionResult Index() { if (User.Identity.IsAuthenticated) { string loginId = User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Sid).Value; string name = User.Identity.Name; } return View(); } }
登录后,关闭浏览器,再次打开 Home/Index,User.Identity.IsAuthenticated 仍然是 True。 没有设置 Cookie 过期日期,关闭浏览器 Cookie 不是应该自动失效了吗?
解決了,是我的錯!
我是关闭了浏览器(不是浏览器里的Tab)。但是,原因还是我没“彻底”关闭浏览器:一上班就用谷歌浏览器打开了博客园,浏览了博客园最新更新的文章,然后打开vs2017 coding...,按F5调试运行,vs自动开启了另一个谷歌浏览器实例(不是Tab)显示网页,于是就发现这个问题,发现“关闭浏览器”,cookie没自动清空。。。其实,我只是关闭了调试程序的谷歌浏览器实例,早上打开博客园的谷歌浏览器实例一直没关。。。。要关闭浏览器所有Tab、所有实例,下次启动浏览器才会清除Session Cookie. 是我太粗心了,急于看到结果,对cookie的机制理解的不够深刻!
学编程你要记住一点,所有的自动都是别人自己动手完成的。
你的岁月静好,那是因为有人在那儿默默的编程....
好文,这个问题我也遇到了,谢谢解答