.Net Core 学习使用Session、和Cookie验证身份
一、使用Session
1.1 Status.cs 中配置
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = "haos.Session"; options.IdleTimeout = TimeSpan.FromHours(1);//设置session的过期时间 options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSession(); //在UseMvc前调用 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
1.2 session必须在浏览器中,调用才有效果。
二、Cookie验证身份
2.1 Status.cs 中配置
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthentication("haos") .AddCookie("haos", (option) => { option.LoginPath = "/Account/login"; option.LogoutPath = "/Account/logout"; option.ExpireTimeSpan = TimeSpan.FromDays(1); option.AccessDeniedPath = new PathString("/Account/Login"); option.Cookie = new CookieBuilder() { Name = "haos.develop" }; }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); }
2.2 实现登录方法
public async Task LoginSignIn(object member) { var identity = new Claim[] { new Claim(ClaimTypes.Name, ""), new Claim(ClaimTypes.MobilePhone, ""), new Claim(ClaimTypes.PrimarySid,""), new Claim("id",""), }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(identity, "haos")), new AuthenticationProperties() { ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromDays(7)), IsPersistent = true }); }