標籤:tom asc email cookie stomp request identity value generic
1 1.自訂實現IPrincipal介面的類 2 interface ICustomPrincipal : IPrincipal 3 { 4 string Identifier { get; set; } 5 string IdentityType { get; set; } 6 } 7 public class CustomPrincipal : ICustomPrincipal 8 { 9 public IIdentity Identity { get; private set; }10 public bool IsInRole(string role) { return false; }11 public CustomPrincipal()12 {13 }14 public CustomPrincipal(string identifer)15 {16 this.Identity = new GenericIdentity(identifer);17 }18 19 public CustomPrincipal(IIdentity identity)20 {21 this.Identity = identity;22 }23 24 public string Identifier25 {26 get;27 set;28 }29 30 public string IdentityType31 {32 get;33 set;34 }35 }36 public class CustomPrincipalSerializeModel37 {38 public string Identifier { get; set; }39 public string IdentityType { get; set; }40 }41 2.登入成功,儲存相關登入資訊42 CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();43 serializeModel.Identifier = model.Account;44 serializeModel.IdentityType = "email";45 46 JavaScriptSerializer serializer = new JavaScriptSerializer();47 48 string userData = serializer.Serialize(serializeModel);49 50 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(51 1,52 model.Account,53 DateTime.Now,54 DateTime.Now.AddMinutes(15),55 false,56 userData);57 58 string encTicket = FormsAuthentication.Encrypt(authTicket);59 HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);60 Response.Cookies.Add(faCookie);61 3.在Global檔案中註冊Application_PostAuthenticateRequest事件62 protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)63 {64 HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];65 66 if (authCookie != null)67 {68 FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);69 70 JavaScriptSerializer serializer = new JavaScriptSerializer();71 72 CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);73 74 CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);75 newUser.Identifier = serializeModel.Identifier;76 newUser.IdentityType = serializeModel.IdentityType;77 78 HttpContext.Current.User = newUser;79 }80 81 }82 4.在BaseController中擷取登入相關資訊83 protected virtual new CustomPrincipal User84 {85 get { return HttpContext.User as CustomPrincipal; }86 }87 5.方法中使用88 User.Identifier
.net mvc 擴充IPrincipal介面