码迷,mamicode.com
首页 > 其他好文 > 详细

自定以身份认证

时间:2015-04-28 17:48:03      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

自定以身份认证需要继承IIdentity与IPrincipal这两个接口来实现,这个过程是在AuthenticateRequest阶段完成的。以下过程都是模拟实现身份认证的,通过这种方式可以将ticket中保存的数据取出来用于初始化IPrincipal的实现,从而改变HttpContext.Current.User的指向的对象实例。

技术分享
  <authentication mode="Forms">
            <forms loginUrl="a.html" name="andy"></forms>
        </authentication>
View Code
技术分享
 1     public class MyPrincipal : IPrincipal
 2     {
 3         public IIdentity Identity
 4         {
 5             get { return new MyIdendity("aa"); }
 6         }
 7 
 8         public bool IsInRole(string role)
 9         {
10             if (string.Compare(role, "a,b", true) == 0)
11             {
12                 return true;
13             }
14             else
15             {
16                 return false;
17             }
18         }
19     }
View Code
技术分享
 1   public class MyIdendity : IIdentity
 2     {
 3 
 4         public MyIdendity(string data)
 5         { 
 6           
 7         }
 8         public string AuthenticationType
 9         {
10             get { return "MyIdendity"; }
11         }
12 
13         public bool IsAuthenticated
14         {
15             get { return true; }
16         }
17 
18         public string Name
19         {
20             get { return "andy"; }
21         }
22     }
View Code
技术分享
 1   protected void Page_Load(object sender, EventArgs e)
 2         {
 3             string userRoles = "admin,test";
 4             FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
 5                 1,
 6                 "a",
 7                 DateTime.Now,
 8                 DateTime.Now.AddMinutes(30),
 9                 true,
10                userRoles,
11                "/"
12                 );
13             string haskTicket = FormsAuthentication.Encrypt(ticket);
14             HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName,haskTicket);
15             Response.Cookies.Add(userCookie);
16         
17         }
18 
19         protected void Button1_Click(object sender, EventArgs e)
20         {
21             var context = HttpContext.Current;
22             if (context.User.Identity is FormsIdentity)
23             {
24                 if (!(context.User is MyPrincipal))
25                 {
26                     FormsIdentity forms = (FormsIdentity)context.User.Identity;
27                     string data = forms.Ticket.UserData;
28                     MyPrincipal principal = new MyPrincipal();
29                     context.User = principal;
30                 }
31             }
32         }
33     }
View Code

 

自定以身份认证

标签:

原文地址:http://www.cnblogs.com/goodlucklzq/p/4409107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!