背景:以前做登錄時用的都是FormsAuthentication.SetAuthCookie(model.UID, IsRemeber),但是有一個不好,不能存儲多個值,有時候我們既想存儲登錄用戶的UID又想存儲用戶名,以前都是將兩者拼接成字元串,用的時候在split出來,比較麻煩,現在用Claim ...
背景:以前做登錄時用的都是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>
好了,好像就這麼多了,結束!!!!!!