Forms身份验证自已总结的解决方案

一:web.config配制文件

<authentication mode="Forms">
        
<forms name="HuiBao" loginUrl="logon.aspx" protection="All" timeout="60" path="/">
        
</forms>
 
</authentication> 
<authorization>
        
<deny users="?" />
        
<allow users="*" /> 
</authorization> 

     
<location path="EditAccount.aspx">
          
<system.web>
               
<authorization>
                    
<allow roles="Mean"/>
                    
<deny users="*" />
               
</authorization>
       
</system.web>
  
</location>//这里用限制某一目录下的页面或某一页中可以访问的角色,如果角色不对,自动导向到Logon.aspx页面,很方便,但缺点是人性化不高,不能弹出提示,所以下面用在每个页面的pageLoad事件里判断角色再转向。

二:Logon.aspx页面
//在用户登录验证完毕后调用此方法写cookie,用户名作cookie名,用户角色 作为cookie的内容

private void setCook(string userName,string userRole)
  
{
         HttpCookie hk;
         FormsAuthenticationTicket Fat ;
         Fat 
= new FormsAuthenticationTicket(1,userName,DateTime.Now,DateTime.Now.AddMinutes(30),false,userRole);
         
string hashTicket = FormsAuthentication.Encrypt(Fat);
         hk 
= new HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);
         hk.Expires
=Fat.Expiration;
         HttpContext.Current.Response.Cookies.Add(hk);     
  }

此方法底下还有两句,导到原请求页面去的,但在第一次登录的时候会自动导到default.aspx页面,所以取消了。

1string requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);
2HttpContext.Current.Response.Redirect(requestUrl);

三:Global.asax页面


protected void Application_AuthenticateRequest(Object sender, EventArgs e)
  
{
      
if(HttpContext.Current.User!=null)       //验证用户不为空
      {
          
if(HttpContext.Current.User.Identity.IsAuthenticated)//是通过验证了的
          {
                 FormsIdentity fi 
= (FormsIdentity)HttpContext.Current.User.Identity;  //Forms身份验证
                 FormsAuthenticationTicket ticket = fi.Ticket;    //取得票据
                 string userData = ticket.UserData;                      //取得信息         
                 string[] roles = userData.Split(',');
                 HttpContext.Current.User 
= new GenericPrincipal(fi,roles);    //把角色信息写入当前用户
          }

      }

  }

四:在任意页面中

private void Page_Load(object sender, System.EventArgs e)
  
{
         
// 在此处放置用户代码以初始化页面
         if(HttpContext.Current.User.IsInRole("Adminisrator"))
         
{
                         Response.Write(
"是这个角色");//做你想要的操作
         }

         
else
         
{
                             //先弹出提示然后再导向到登录页面。  如果不用提示,则前的的配制节就可以了0
                
         Response.Write("<script language='javascript'>if(window.opener == null){alert('对不起,您无权访问这个页面,请登录')};location.href('Logon.aspx')</script>");   
                     }

  }

//注销

FormsAuthentication.SignOut();//注销 
Response.Redirect("logon.aspx",true);
posted on 2005-11-18 13:46  泽来  阅读(964)  评论(1编辑  收藏  举报