天天看点

web的用户验证方式

最近,看了一些MS的portal源程序,对于其中的用户验证觉的很感兴趣。特整理注释如下:

Web.Config的配置:

<authentication mode="Forms" >   //窗体验证方式

<forms name="EDEMO" loginUrl="WebForm1.aspx" protection="All" timeout="30" ></forms>  //如果未通过则转向WebForm1.aspx

</authentication>

<authorization>

<deny users="?" />       //拒绝未通过验证的用户

<allow users="*" />      //允许通过验证的用户

</authorization>

Global.ascx:

   if(Request.IsAuthenticated==true)      //如果通过了验证

   {

    if(Request.Cookies["role"]==null)     //Cookie里面没有保存角色信息

    {

     GenericIdentity id = new GenericIdentity(User.Identity.Name.ToString());  //创建一个新的用户身份,User.Identity.Name为当前通过验证的用户名

     Class1 c2= new Class1();

     DataTable dt2=c2.UserRole(User.Identity.Name.ToString()).Tables[0];

     String[] s=new string[dt2.Rows.Count];

     for(int i=0;i<dt2.Rows.Count;i++)

     {

      s[i]=dt2.Rows[i][1].ToString();

      Response.Cookies["role"].Value+=s[i].ToString()+"/";   //注意cookies不要用;分割

     }  //得到用户的角色信息

     Context.User=new GenericPrincipal(id,s); //角色赋予当前用户   

    }

    else

    {

     GenericIdentity id = new GenericIdentity(User.Identity.Name.ToString());

     string[] s=Request.Cookies["role"].Value.ToString().Split(new char[]{'/'});

     Context.User=new GenericPrincipal(id,s); 

    }

   }

   DataTable dt=c.user(TextBox1.Text.ToString(),TextBox2.Text.ToString()).Tables[0];

   if(dt.Rows.Count>0)   //如果通过了密码校验

   {

    System.Web.Security.FormsAuthentication.SetAuthCookie(TextBox1.Text,true);   //通过验证

    Response.Redirect("WebForm2.aspx");

   }

                        Context.User.IsInRole("admin")   //当前用户是否属于“admin”角色

登出:               System.Web.Security.FormsAuthentication.SignOut();