Asp.Net Core 简单的使用加密的Cookie保存用户状态
2016-11-02 17:50
881 查看
在以前的Asp.Net中可以用 FormsAuthentication 类的一系列方法来使用加密的Cookie存储用户身份,使用简单,可控性强。在Asp.Net Core中是否也可以的?答案是当然的。
使用步骤:
1、在 project.json 中添加项目依赖 "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0":
2、在 Startup.cs 中添加中间件:
3、创建一个新的 Controller,并添加登录的方法,大致如下:
4、退出登录方法:
5、获取用户信息:
其它说明:
这里生成的Cookie是加密过的,大概如下:
相关的Cookie名称,域,过期时间等都可以在 Startup.cs 中进行设置,大概如下:
步骤很简单,也是极好用的,若结合是否自动启用验证的AutomaticAuthenticate来进行Area分区域认证,灵活性更强。
使用步骤:
1、在 project.json 中添加项目依赖 "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0":
"dependencies": { "Microsoft.NETCore.App": { "version": "1.0.1", "type": "platform" }, "Microsoft.AspNetCore.Diagnostics": "1.0.0", "Microsoft.AspNetCore.Mvc": "1.0.1", "Microsoft.AspNetCore.Razor.Tools": { "version": "1.0.0-preview2-final", "type": "build" }, "Microsoft.AspNetCore.Routing": "1.0.1", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.1", "Microsoft.AspNetCore.StaticFiles": "1.0.0", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0", "Microsoft.Extensions.Logging": "1.0.0", "Microsoft.Extensions.Logging.Console": "1.0.0", "Microsoft.Extensions.Logging.Debug": "1.0.0", "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0", "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0" }
2、在 Startup.cs 中添加中间件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "member", // Cookie 验证方案名称,后面多处都需要用到,部分地方必须要求常量,所以直接配置为字符串。 AutomaticAuthenticate = true, // 是否自动启用验证,如果不启用,则即便客服端传输了Cookie信息,服务端也不会主动解析。 // 除了明确配置了 [Authorize(ActiveAuthenticationSchemes = "上面的方案名")] 属性的地方,才会解析,此功能一般用在需要在同一应用中启用多种验证方案的时候。比如分Area. LoginPath = "/account/login" // 登录页 }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
3、创建一个新的 Controller,并添加登录的方法,大致如下:
[AllowAnonymous] public async Task<IActionResult> Login() { // 这里应该写业务逻辑来获取用户名,用户Id等信息。 var userId = 10000; var userName = "admin"; // ======================== var identity = new ClaimsIdentity("Forms"); // 指定身份认证类型 identity.AddClaim(new Claim(ClaimTypes.Sid, userId.ToString())); // 用户Id identity.AddClaim(new Claim(ClaimTypes.Name, userName)); // 用户名称 var principal = new ClaimsPrincipal(identity); await HttpContext.Authentication.SignInAsync("member", principal, new AuthenticationProperties { IsPersistent = true }); string returnUrl = Request.Query["returnUrl"]; if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); return RedirectToAction("index", "account");
}
4、退出登录方法:
public async Task<IActionResult> Logout() { await HttpContext.Authentication.SignOutAsync("member"); // Startup.cs中配置的验证方案名 return RedirectToAction("index", "home"); }
5、获取用户信息:
[Authorize(ActiveAuthenticationSchemes = "member")] public IActionResult Index() { var userId = User.FindFirst(ClaimTypes.Sid).Value; var userName = User.Identity.Name; return Json(new { Id = userId, Name = userName }); }
其它说明:
这里生成的Cookie是加密过的,大概如下:
相关的Cookie名称,域,过期时间等都可以在 Startup.cs 中进行设置,大概如下:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "member", // 验证方案名 AutomaticAuthenticate = true, // 是否自动启用验证 LoginPath = "/account/login", // 登录地址 CookieDomain = "abc.com", // 验证域 CookieName = "abc", // Cookie 名称 CookiePath = "/", // Cookie 路径 ExpireTimeSpan = TimeSpan.FromDays(3), // 过期时间 SlidingExpiration = true, // 是否在过期时间过半的时候,自动延期 CookieHttpOnly = true // 是否允许客户端Js获取。默认True,不允许。 });
步骤很简单,也是极好用的,若结合是否自动启用验证的AutomaticAuthenticate来进行Area分区域认证,灵活性更强。
相关文章推荐
- [转]Asp.Net Core 简单的使用加密的Cookie保存用户状态
- Asp.Net使用加密cookie代替session验证用户登录状态 源码分享 欢迎拍砖
- Asp.Net使用加密cookie代替session验证用户登录状态 源码分享
- ASP.NET使用Cookie简单实现记住登陆状态功能
- ASP.NET使用Cookie简单实现记住登陆状态功能
- ASP.net core 2.0.0 中 asp.net identity 2.0.0 的基本使用(三)—用户账户及cookie配置
- 使用COOKIE对像实现保存用户基本信息(结合Session),ASP.Net实现用户登录全过程
- 在无cookie模式中,会话话状态的ID将会自动保存在ASP.NET的查询字符串中
- 一步一步使用Ext JS MVC与Asp.Net MVC 3开发简单的CMS后台管理系统之用户管理(1)
- 一步一步使用Ext JS MVC与Asp.Net MVC 3开发简单的CMS后台管理系统之用户管理(1)
- ASP.NET jQuery 实例12 通过使用jQuery validation插件简单实现用户注册页面验证功能
- 一步一步使用Ext JS MVC与Asp.Net MVC 3开发简单的CMS后台管理系统之用户管理(1)
- ASP.NET jQuery 实例11 通过使用jQuery validation插件简单实现用户登录页面验证功能
- ASP.NET WEB群集使用SQL Server保存状态
- 在ASP.NET AJAX中使用应用程序服务和本地化(4):示例程序:读取、修改并保存用户个性化信息
- 使用ASP.Net加密Cookie[1]
- [ASP.NET]配置使用SQL Server保存会话状态
- ASP.NET jQuery 食谱11 (通过使用jQuery validation插件简单实现用户登录页面验证功能)
- asp.net中httpcookie 的使用和简单计数器
- ASP.NET WEB群集使用SQL Server保存状态