首页 > 代码库 > .net mvc 扩展IPrincipal接口

.net mvc 扩展IPrincipal接口

 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 Identifier
25     {
26         get;
27         set;
28     }
29 
30     public string IdentityType
31     {
32         get;
33         set;
34     }
35 }
36 public class CustomPrincipalSerializeModel
37 {
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 =http://www.mamicode.com/ 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 User
84 {
85     get { return HttpContext.User as CustomPrincipal; }
86 }
87 5.方法中使用
88 User.Identifier

 

.net mvc 扩展IPrincipal接口