目录 admin/Default.aspx
     Login.aspx
     Web.Config下面的这样做导致无法转到Default.aspx页
但实际上是重定向到了Default.aspx,但是因为web.config里的配置又转到了login.aspx,这样的原因是用户不满足web.config里面的配置,但在Application_AuthorizeRequest事件中我判断过Ctx.User.IsInRole("Admin")是等于true,就是说当前用户在global中可以检测到是属于Admin角色的,想不通啊
 global.asax文件:   
  using   System;   
  using   System.Collections;   
  using   System.ComponentModel;   
  using   System.Web;   
  using   System.Web.SessionState;   
  using   System.Web.Security;   
  using   System.Security.Principal;   
    
  namespace   DotNetStudy     
  {   
  ///   <summary>   
  ///   Global   的摘要说明。   
  ///   </summary>   
  public   class   Global   :   System.Web.HttpApplication   
  {   
  public   Global()   
  {   
  InitializeComponent();   
  }   
    
  protected   void   Application_Start(Object   sender,   EventArgs   e)   
  {   
    
  }   
      
  protected   void   Session_Start(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  protected   void   Application_BeginRequest(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  protected   void   Application_EndRequest(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  protected   void   Application_AuthorizeRequest(object   sender,   System.EventArgs   e)   
  {   
  HttpApplication   App   =   (HttpApplication)   sender;   
  HttpContext   Ctx   =   App.Context   ;   //获取本次Http请求相关的HttpContext对象   
  if   (Ctx.Request.IsAuthenticated   ==   true)   //验证过的用户才进行role的处理   
  {   
  FormsIdentity   Id   =   (FormsIdentity)Ctx.User.Identity   ;   
  FormsAuthenticationTicket   Ticket   =   Id.Ticket   ;   //取得身份验证票   
  string[]   Roles   =Ticket.UserData.Split   (',')   ;   //将身份验证票中的role数据转成字符串数组   
  Ctx.User   =   new   GenericPrincipal(Id,   Roles)   ;   //将原有的Identity加上角色信息新建一GenericPrincipal表示当前用户,这样当前用户就拥有了role信息   
  }   
  }   
    
  protected   void   Application_AuthenticateRequest(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  protected   void   Application_Error(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  protected   void   Session_End(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  protected   void   Application_End(Object   sender,   EventArgs   e)   
  {   
    
  }   
    
  #region   Web   Form   Designer   generated   code   
  ///   <summary>   
  ///   设计器支持所需的方法   -   不要使用代码编辑器修改   
  ///   此方法的内容。   
  ///   </summary>   
  private   void   InitializeComponent()   
  {           
  }   
  #endregion   
  }   
  }   
  ————————————————————————————————————   
  Login.aspx   
  <%@   Import   Namespace="System.Security.Principal"   %>   
  <%@   Import   Namespace="System.Data.SqlClient"   %>   
  <%@   Import   Namespace="System.Web.Security   "   %>   
  <HTML>   
  <script   language="C#"   runat="server">   
  string   urole="";   
    
  private   void   Login_Click(object   sender,   System.EventArgs   e)   
  {   
  string   user   =   UserName.Value;   //读取用户名   
  string   password   =   UserPass.Value;   //读取密码   
  FormsAuthentication.SignOut();   
  if   (ValidateUser(user,password))     
  {   
  FormsAuthenticationTicket   Ticket   =   new   FormsAuthenticationTicket(1,user,DateTime.Now,DateTime.Now.AddMinutes(30),   false,urole,"/")   ;   //建立身份验证票对象   
  string   HashTicket   =   FormsAuthentication.Encrypt(Ticket)   ;   //加密序列化验证票为字符串   
  HttpCookie   UserCookie   =   new   HttpCookie(FormsAuthentication.FormsCookieName,   HashTicket)   ;     
  //生成Cookie   
  Context.Response.Cookies.Add(UserCookie)   ;   //输出Cookie   
    
  Context.Response.Redirect(Context.Request["ReturnUrl"])   ;   //   重定向到用户申请的初始页面   
  }   
  else     
  {   
  Msg.Text   =   "凭据无效:请再试一次";   
  }   
  }   
    
  private   bool   ValidateUser(string   uid,   string   passwd)   
  {   
  SqlConnection   cnn;   
  SqlCommand   cmd;   
  SqlDataReader   dr;   
  cnn   =   new   SqlConnection("server=san;uid=NetGame;pwd=123456;database=NetGameCard");   
  cmd   =   new   SqlCommand("Select   *   from   users   where   uname='"   +   uid   +   "'",cnn);   
  cnn.Open();   
  dr   =   cmd.ExecuteReader();   
  while   (dr.Read())   
  {   
        
  if   (dr["Pwd"].ToString().Trim()==passwd)   
  {   
  urole=dr["userRole"].ToString().Trim()+",";   
  cnn.Close();   
  return   true;   
  }   
  }   
  cnn.Close();   
  return   false;   
  }   
  </script>   
  <body>   
  <form   id="Form1"   runat="server">   
  <h3><font   face="宋体">登录页</font></h3>   
  <table>   
  <tr>   
  <td>用户名:</td>   
  <td><input   id="UserName"   type="text"   name="UserName"   runat="server"></td>   
  <td><ASP:REQUIREDFIELDVALIDATOR   id="Requiredfieldvalidator1"   runat="server"   ErrorMessage="*"   Display="Static"   ControlToValidate="UserName"></ASP:REQUIREDFIELDVALIDATOR></td>   
  </tr>   
  <tr>   
  <td>密码:</td>   
  <td><input   id="UserPass"   type="password"   name="UserPass"   runat="server"></td>   
  <td><ASP:REQUIREDFIELDVALIDATOR   id="Requiredfieldvalidator2"   runat="server"   ErrorMessage="*"   Display="Static"   ControlToValidate="UserPass"></ASP:REQUIREDFIELDVALIDATOR></td>   
  </tr>   
  <tr>   
  <td>持久的   Cookie:</td>   
  <td><ASP:CHECKBOX   id="PersistCookie"   runat="server"></ASP:CHECKBOX></td>   
  <td></td>   
  </tr>   
  </table>   
  <FONT   face="宋体">   
  <BR>   
  <asp:button   id="Button1"   OnClick="Login_Click"   runat="server"   Text="SignIn"></asp:button><BR>   
  <BR>   
  </FONT>   
  <p><asp:label   id="Msg"   runat="server"   Font-Size="10"   Font-Name="Verdana"   ForeColor="red"></asp:label></p>   
  </form>   
  </body>   
  </HTML>   
  ______________________________________________________________________   
  web.config  
         <system.web>
        <authentication   mode="Forms">   
              <forms   name="ASPXAUTH"   loginUrl="~/Login.aspx"   path="/"   timeout="30"   />   
        </authentication>   
        <authorization>   
              <deny   users=""   />   
        </authorization> 
         <system.web>  <location path="admin">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  _______________________________________________________________________   
  Default.aspx   
  <%@   Import   Namespace="System.Web.Security   "   %>   
  <HTML>   
  <script   language="C#"   runat="server">   
  void   Page_Load(Object   Src,   EventArgs   E   )   
  {   
  Welcome.Text   =   "Hello,   "   +   User.Identity.Name;   
  if(HttpContext.Current.Request.IsAuthenticated==true)   
  {   
  System.Web.Security.FormsIdentity   Id   =   (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;   
  System.Web.Security.FormsAuthenticationTicket   Ticket   =   Id.Ticket   ;   //取得身份验证票   
  string[]   Roles   =   Ticket.UserData.Split   (',')   ;   //将身份验证票中的role数据转成字符串数组   
  //string   LoginName=HttpContext.Current.User.Identity.Name.ToString();   
  Welcome.Text=Roles[0];   
  Response.Write(HttpContext.Current.User.IsInRole("Admin"));   
  }   
  }   
    
          void   Signout_Click(Object   sender,   EventArgs   E)   
          {   
            FormsAuthentication.SignOut();   
            Response.Redirect("../Member/Login.aspx");   
          }   
  </script>   
  <body>   
  <h3><font   face="宋体">使用   Cookie   身份验证</font></h3>   
  <form   runat="server"   ID="Form1">   
  <h3><asp:label   id="Welcome"   runat="server"   /><BR>   
  <BR>   
  <asp:Button   id="Button1"   OnClick="Signout_Click"   runat="server"   Text="SignOut"></asp:Button></h3>   
  </form>   
  </body>   
  </HTML>   
  ________________________________________________________________________   
  数据库   
  if   exists   (select   *   from   sysobjects   where   id   =     
  object_id(N'[dbo].[Users]')   and   OBJECTPROPERTY(id,   N'IsUserTable')   =   1)   
  drop   table   [dbo].[Users]   
  GO   
  CREATE   TABLE   [dbo].[Users]   (   
  [uname]   [varchar]   (15)   NOT   NULL   ,   
  [Pwd]   [varchar]   (25)   NOT   NULL   ,   
  [userRole]   [varchar]   (25)   NOT   NULL   ,   
  )     ON   [PRIMARY]     
  GO   
  ALTER   TABLE   [dbo].[Users]   WITH   NOCHECK   ADD     
  CONSTRAINT   [PK_Users]   PRIMARY   KEY     NONCLUSTERED     
        (   
  [uname]   
  )     ON   [PRIMARY]     
  GO   
    
  INSERT   INTO   Users   values('user1','user1','Manager')   
  INSERT   INTO   Users   values('user2','user2','Admin')   
  INSERT   INTO   Users   values('user3','user3','User')   
  GO

解决方案 »

  1.   

    allow,deny要怎么写才能限制角色访问呢
      

  2.   

    只知道RBAC,在这里配置不会, 继续关注中。。
      

  3.   

    为何:Application_AuthorizeRequest事件改为Application_AuthenticateRequest事件才能实现
      

  4.   

    string  urole="Admin";  你怎么写的空。
      

  5.   

    <configuration> 
    <system.web> 
    <authentication mode="Forms"> 
    <forms name="MYWEBAPP.ASPXAUTH" loginUrl="login.aspx" 
    protection="All" path="/"/> 
    </authentication> 
    <authorization> 
    <allow users="*"/> 
    </authorization> 
    </system.web> 
    <location path="admin"> 
    <system.web> 
    <authorization> 
    <allow roles="Administrator"/> 
    <deny users="*"/> 
    </authorization> 
    </system.web> 
    </location> 
    <location path="users"> 
    <system.web> 
    <authorization> 
    <allow roles="User"/> 
    <deny users="*"/> 
    </authorization> 
    </system.web> 
    </location> 
    </configuration> 
    HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl("", false), true));
      

  6.   

    allow指定允许访问的角色类型。
    deny是不允许访问的。