• 基于角色(RoleBased)的表单验证


    要求:
    using System.Web.Security
    using System.Security.Principal

    [Principal]:主要的(这里怎样翻译呢??)
    ==================================

    目录

    +admin1
     -default.aspx
     -web.config //web.config#1
    +admin2
     -default.aspx
     -web.config//web.config#2
    +bin
    -web.config//web.config#root
    -login.aspx

    ==========================
    目的:
    admin1文件夹:只有role是administrator可以访问.
    admini2文件夹:只有role是controler可以访问.

    帐号,密码,角色存储在特定数据库中.

    本例目的(其他道理相同):
    caca是administrator
    wawa是controler
    所以caca可以访问admin1,不能访问admin2;wawa反之.

    ==========================
    配置:
    (1)web.config#root

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
     
    <system.web>
      
    <authentication mode="Forms">
       
    <forms name="authenticationcookie" 
    loginUrl
    ="login.aspx" protection="All" path="/" timeout="40"/>
      
    </authentication>
     
    </system.web>
    </configuration>

    (2)web.config#1

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
     
    <system.web>
      
    <authorization>
       
    <allow roles="administrator"/>
       
    <deny users="*"/>
      
    </authorization>
     
    </system.web>
    </configuration>

    (3)web.config#2

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
     
    <system.web>
      
    <authorization>
       
    <allow roles="controler"/>
       
    <deny users="*"/>
      
    </authorization>
     
    </system.web>
    </configuration>

    ==========================
    关键代码:
    (1)login.aspx

    <script language=c# runat=server>
    private void signin(Object sender,EventArgs e)
    {
     
    string aRole="guest";
     
    if(tbName.Text=="caca")aRole="administrator";
     
    if(tbName.Text=="wawa")aRole="controler";

     
    //建立role-based认证票据(我认为本质是cookie)
     FormsAuthenticationTicket authTicket = new  FormsAuthenticationTicket(
                 
    1// version(版本?)
                 tbName.Text, // user name(可能是生成票据验证cookie的名称)
                 DateTime.Now, // creation(票据产生时间)
                 DateTime.Now.AddMinutes(40),// Expiration(票据cookie失效时间)
                 false// Persistent(这个应该是票据的保留时间)
                aRole ); // User data(角色)
    //修改票据cookie,使其加密(本质是写入一个与票据cookie同名的新cookie)
     string encryptedTicket = FormsAuthentication.Encrypt(authTicket); 
     HttpCookie authCookie 
    = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);
    //在保存这个Cookie之前,需要设定它的有效时间
    //authCookie.Expires=DateTime.Now.AddDays(3);
     Response.Cookies.Add(authCookie); 
    //返回所请求的URL
     Response.Redirect( FormsAuthentication.GetRedirectUrl(tbName.Text, false ));


    }

    private void signout(Object sender,EventArgs e)
    {
    //注销票据
     FormsAuthentication.SignOut();
    }

    </script>

    <html>
    <head>
    <title>LogIn</title>
    </head>
    <body>
    <form runat=server>
    Name:<asp:textbox runat=server id=tbName/>[caca/wawa]
    <asp:button runat=server text=LogIn onclick=signin/>
    <asp:button runat=server text=SignOut onclick=signout/>
    <hr>
    <asp:label runat=server id=lblMessage/>
    </form>
    </body>
    </html>

    (2)Global.asax

    <% @ import namespace=System.Security.Principal %>
    <% @ import namespace=System.Security %> 
    <script language=c# runat=server>
    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
      
    {

    // Extract the forms authentication cookie(还原加密的票据)
     string cookieName = FormsAuthentication.FormsCookieName;
     HttpCookie authCookie 
    = Context.Request.Cookies[cookieName];
     
    if(null == authCookie)
     
    {
       
    // There is no authentication cookie.
       return;
     }
     
     FormsAuthenticationTicket authTicket 
    = null;
     
    try
     
    {
         authTicket 
    = FormsAuthentication.Decrypt(authCookie.Value);
     }

     
    catch(Exception ex)
     
    {
         
    // Log exception details (omitted for simplicity)
         return;
     }

     
    if (null == authTicket)
     
    {
         
    // Cookie failed to decrypt.
         return
     }

     
    // When the ticket was created, the UserData property was assigned a
     
    // pipe delimited string of role names.(票据已经还原,提取票据的UserData即为验证用户的role)
     string[] roles = authTicket.UserData.Split(new char[]{'|'});

     
    // Create an Identity object
     FormsIdentity id = new FormsIdentity( authTicket ); 
     
    // This principal will flow throughout the request.
     GenericPrincipal principal = new GenericPrincipal(id, roles);
     
    // Attach the new principal object to the current HttpContext object
     Context.User = principal;

    }

    </script>

    ===========================
    参考:
    (1)Building Secure Microsoft ASP.NET Applications:
    Authentication, Authorization, and Secure Communication by Microsoft Corporation  
    ISBN:0735618909
    Microsoft Press
    (2)MSDN
    ===========================
    下载参考代码

  • 相关阅读:
    BCP及自增标识列
    DAC重置max server memory
    登录名与用户名
    重复执行同一命令
    利用DBCC PAGE查看SQL Server中的表和索引数据
    索引约束
    JS高级程序设计笔记一
    div滚动底部加载li,window滚动底部加载li
    懂,才是最好的爱
    CSS3混合模式mix-blend-mode/background-blend-mode简介 ,PS中叠加效果
  • 原文地址:https://www.cnblogs.com/caca/p/27267.html
Copyright © 2020-2023  润新知