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();
在登录页面中调用如下代码
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
});
退出使用
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)