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