背景:以前做登录时用的都是FormsAuthentication.SetAuthCookie(model.UID, IsRemeber),但是有一个不好,不能存储多个值,有时候我们既想存储登录用户的UID又想存储用户名,以前都是将两者拼接成字符串,用的时候在split出来,比较麻烦,现在用ClaimsIdentity就很方便。
1、登录时验证通过存储
ClaimsIdentity ci = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); ci.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, model.UserName)); ci.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.UID)); ci.AddClaim(new Claim("HspUID", model.HspUID)); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = IsRemeber }, ci);
需要用到下面的
private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }
2、获取值
//获取UID User.Identity.GetUserId(); //获取Name User.Identity.Name; //获取HspUID var claimIdentity = (ClaimsIdentity)User.Identity; var HspUID = claimIdentity.FindFirstValue("HspUID");
3、App_Start里创建Startup.Auth.cs
using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Yuwell.PressureManage.Web { public partial class Startup { public void ConfigureAuth(IAppBuilder app) { // 使应用程序可以使用 Cookie 来存储已登录用户的信息 // 并使用 Cookie 来临时存储有关使用第三方登录提供程序登录的用户的信息 // 配置登录 Cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), }); } } }
4、Web项目里添加Startup类
using Hangfire; using Hangfire.MemoryStorage; using Microsoft.Owin; using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Web; [assembly: OwinStartupAttribute(typeof(Test.Web.Startup))] namespace Yuwell.PressureManage.Web { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); GlobalConfiguration.Configuration.UseMemoryStorage(); app.UseHangfireServer(); app.UseHangfireDashboard(); } } }
需要用到的包
记得Web.config里configSections节点下加下面的配置
<system.webServer> <modules> <remove name="FormsAuthentication" /> </modules> </system.webServer>
好了,好像就这么多了,结束!!!!!!