1.须要在Startup ConfigureServices(IServiceCollection services)中 配置以下代码浏览器
#region //身份认证时须要使用的方法 services.AddSession(options=> { options.Cookie.HttpOnly = true; options.Cookie.Name = ApplicationEnvironments.Site.CookieName; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.IdleTimeout = TimeSpan.FromMinutes(ApplicationEnvironments.Site.SessionTimeout); }); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.DataProtectionProvider= DataProtectionProvider.Create(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory+ "/shared-auth-ticket-keys/")); options.Cookie.Name = ApplicationEnvironments.Site.CookieName; options.Cookie.Path = "/"; options.LoginPath = new PathString("/login"); options.AccessDeniedPath = new PathString("/Forbidden"); //禁止访问路径:当用户试图访问资源时,但未经过该资源的任何受权策略,请求将被重定向到这个相对路径。 // options.SlidingExpiration = false; //Cookie能够分为永久性的和临时性的。 临时性的是指只在当前浏览器进程里有效,浏览器一旦关闭就失效(被浏览器删除)。 永久性的是指Cookie指定了一个过时时间,在这个时间到达以前,此cookie一直有效(浏览器一直记录着此cookie的存在)。 slidingExpriation的做用是,指示浏览器把cookie做为永久性cookie存储,可是会自动更改过时时间,以使用户不会在登陆后并一直活动,可是一段时间后却自动注销。也就是说,你10点登陆了,服务器端设置的TimeOut为30分钟,若是slidingExpriation为false,那么10:30之后,你就必须从新登陆。若是为true的话,你10:16分时打开了一个新页面,服务器就会通知浏览器,把过时时间修改成10:46。 更详细的说明仍是参考MSDN的文档。 }); #endregion services.MVC() .AddSessionStateTempDataProvider();
在Configure(IApplicationBuilder app, IHostingEnvironment env)添加以下代码服务器
app.UseAuthentication();
在登陆页面中调用以下代码cookie
var claims = new List<Claim>() { new Claim(ClaimTypes.Name,model.UserName) , new Claim(ClaimTypes.NameIdentifier,model.UserId.ToString() ) var Identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); Identity.AddClaims(claims); //init the identity instances var userPrincipal = new ClaimsPrincipal(Identity); }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTimeOffset.Now.AddMinutes(ApplicationEnvironments.Site.SessionTimeout), IsPersistent = true, AllowRefresh = true });
退出使用app
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)ide