验证

来源:互联网 发布:软件系统设计是什么 编辑:程序博客网 时间:2024/05/09 00:12

Asp.Net基于forms的验证机制

最近在看asp.net forum,对其中的验证机制看得模模糊糊,看完构建安全的 ASP.NET 应用程序中的表单身份验证部分,思路就很清晰了,稍做了点记录,以便查阅:

构建基于forms的验证机制过程如下:
1,设置IIS为可匿名访问和asp.net web.config中设置为form验证
2,检索数据存储验证用户,并检索角色(如果不是基于角色可不用)
3,使用FormsAuthenticationTicket创建一个Cookie并回发到客户端,并存储
  角色到票中,如:
  FormsAuthentication.SetAuthCookie(Username,true | false)
  cookies保存时间:
  HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires=DateTime.Now.AddDays(1)

  如果需要存储角色,采用:
 FormsAuthenticationTicket authTicket = new
 FormsAuthenticationTicket(
            1, // version
            txtUserName.Text, // user name
            DateTime.Now, // creation
            DateTime.Now.AddMinutes(20),// Expiration
            false, // Persistent
            roles ); // User data
  roles是一个角色字符串数组
  string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密

  存入Cookie
  HttpCookie authCookie =
  new HttpCookie(FormsAuthentication.FormsCookieName,
  encryptedTicket);

  Response.Cookies.Add(authCookie);

4,在Application_AuthenticateRequest事件中处理程序中(Global.asax)中,使用
  票创建IPrincipal对象并存在HttpContext.User中
  代码:
  HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
  FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密
  string[] roles = authTicket.UserData.Split(new char[]{';'});//根据存入时的格式分解,;或|....
  Context.User = new GenericPrincipal(Context.User.Identity, Roles);//存在HttpContext.User中

5,需要对某些页面进行角色控制,有两种方法:
 5.1,web.config中加
   
 
  
                       
   
  

 

   

 5.2,把只能是某种角色访问的文件放在同一目录下,在此目录下添加一个web.config
  
    
 
          
   
 

    

  

  说明:子目录的web.config设置优先于父目录的web.config设置

 

Asp.Net安全验证小结

1,基于windows的安全验证
 web.config文件:
 
   
       
       
       
           
           
       

   

 

  在.aspx文件中无需任何代码就可以实现验证,但可以在.aspx文件获取登陆用户的信息
  需导入命名空间:System.Security.Principal
  if(User.Identity.IsAuthenticated)//判断用户是否验证,似乎可有可无
  {
    WindowsIdentity objWinIdentity=WindowsIdentity.GetCurrent();
    lblHelloMsg.Text="the name:"+objWinIdentity.Name+"
Type:"+ objWinIdentity.AuthenticationType+"IsInRole:"+User.IsInRole("computername//groupname");
  }
 
2,基于web.config forms验证
 web.config文件:
 

 
               protection="All" timeout="30">
     
       
       
     

   

 

 
   
   
 



 login.aspx文件:需要提供两个文本框用于填写用户和密码(txtUsr,txtPwd),一个单选框判断是否永久保存
                还需要一个按钮控件则响应该button的代码如下:
void DoLogin(Object sender, EventArgs e)
{
   if(FormsAuthentication.Authenticate(txtUsr.Value,txtPwd.Value))
   {
       FormsAuthentication.RedirectFromLoginPage(txtUsr.Value,chkPersist.Checked);
   }
   else
   //为代码完整性而设置,可以不写
   {
       Response.Write("authentication fails");
   }

然后在别的页面可以获得登陆用户的值:
if(User.Identity.IsAuthenticated)//可以不需要判断
{
  Response.Write("your name:"+User.Identity.Name);
  Response.Write("验证类型:"+User.Identity.AuthenticationType);//forms,windows等
}

3,基于自定义forms验证
 web.config文件(基本上不需要什么设置):
  
  
        protection="All"  timeout="30" >
  

  

  
  
  

 
  custom-login.aspx文件,基本原理还是跟2中说的一样,如:
  if (blnIsAuthenticated) //注意这个blnIsAuthenticated是一个自己定义的变量
  //当我们把用户输入的信息和数据库(或xml)的信息比对,存在则把该变量设为true,反之false
  //这是跟2不一样的地方
  {
     FormsAuthentication.RedirectFromLoginPage(txtUsr.Value, chkPersist.Checked);
     //txtUsr和chkPersist分别为textbox,checkbox控件
  }
  else
  {
    //验证失败提示信息
  }
  剩下的如在其他页面获得用户信息,如2一样
 
4,退出登陆
响应退出登陆按钮的代码:
FormsAuthentication.SignOut();
Response.Clear();
Response.Redirect(Request.UrlReferrer.ToString());//重定向到前一个页面

 

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();

原创粉丝点击