关于进行Asp.net窗体验证的过程说明

  开发 asp.net 程序 时最常用的验证模式就是基于窗体的身份验证模式,结合 global.asawebconfig 可以 快速实现此种机制。笼统的说,该过程是先建一个文件夹,然后把要保护的页面放进去,接着设置一下web,config,这样就完成了保护。如果你要访问这个文件夹,就会被强制转到预先设定的登录页面,你填上正确的用户名和密码,提交,系统验证后,就把你的登陆信息写到cookie里面,这样你再去访问那个文件夹,就可以进去了,因为你的登陆凭证已经保存到cookie里面了。
    先要建一个asp.net应用程序,这里面至少要有一个登录用的页面,然后修改你的根目录下的web.config,把验证那一块改成Forms验证模式。
  < authentication mode = " Forms " >
       < forms loginUrl = " Login.aspx "  />
  </ authentication >
  < authorization >
      < deny users = " ? "  />
  </ authorization >

     接下来在要保护的文件夹里放一个web.config,要注意的是,这个子文件夹里的web.config的实际内容不能像根目录下的那个一样多,否则就会出现“配置错误”,提示“在应用程序级别以外使用注册为 allowDefinition='MachineToApplication' 的节是错误的。导致该错误的原因可能是在 IIS 中没有将虚拟目录作为应用程序进行配置。”具体应该怎么做我也不清楚,总之这个web.config只要有下面的内容就ok了。
   

< configuration >
   < system.web >
     < authorization >
      <!-- 设置准许访问此文件夹的角色和拒绝的角色,这里准许管理员,老师访问,拒绝学生访问 -->
        < allow roles = " admin "  />
        < allow roles = " teacher "  />
        < deny roles = " student "  />
        <!-- 前提是拒绝匿名用户 !-->
        < deny users = " ? "  />
     </ authorization >
  </ system.web >
</ configuration >

  当然也可以在顶层web.config文件中完成所有的url授权,而不是把它们分在各自目录下的web,config文件中。asp.net也支持这种做法。下面这个web,config文件,放在应用程序根目录下。
 如下:此设置是保护admin文件夹下的内容,拒绝匿名用户访问
 

< location path = " admin " >
   < system.web >
    < authorization >
      < deny users = " ? " ></ deny >
    </ authorization >
    </ system.web >
</ location >

   好了,设置完了,下面就开始为我们的窗体验证写代码了
   有两种方式,第一种,当网站的用户不是很多的时候,可以把用户和密码放到web.config里。办法就是在根目录下的web.config文件中加入一个credentials节,里面写上用户名和密码,这个是包含在forms节里面的。
   如下所示:

< authentication mode = " Forms "  >
    < forms loginUrl = " login.aspx " >
      < credentials passwordFormat = " Clear " >
       < user name = " admin "  password = " admin " />
      </ credentials >
    </ forms >
</ authentication >

   在此种情况下  配合使用System.Web.Security.FormsAuthentication.Authenticate(string name,string password)验证credentials节中指定的用户名和密码,存在就返回true。


  下面着重介绍第二种方法,通过数据库读取用户名密码进行验证。
    1:首先在数据库里建立三张表: Users(UserID,UserName,UserPwd)---存放用户信息
                              Roles(RoleID,RoleName)------存放角色名称
                              User_Role(UserID,RoleID)-----用户和角色的中间表,使头两张表成为多对多关系

    2:然后在登陆页面的登陆按钮点击事件中加入如下逻辑
 

if  (Page.IsValid) 
        {
            if(Users.Authenticate(txtUsername.Text, txtPassword.Text))//数据库验证方法,代码略
            {
                 //验证后导向初始页
                   FormsAuthentication.RedirectFromLoginPage( txtUsername.Text, chkRemember.Checked ;
               }

        }

    在此也可以用 FormsAuthentication.SetAuthCookie(email.Text, RememberCheckbox.Checked);该方法不进行页面导向,而是停留在本页,然后由自己选择导向的页面。

    3:然后就要用到global.asax文件下的Application_AuthenticateRequest事件了,此事件在每次访问aspx文件都会触发。
在其中加入如下代码,功能见注释:
   

protected  void  Application_AuthenticateRequest(Object sender, EventArgs e)
         {
            
            if (Request.IsAuthenticated == true) //如果验证了用户,则为 true,否则为 false
            {  
                String[] roles;
                // 首次登陆,还没有存入角色cookies
                if ((Request.Cookies["userlroles"] == null) || (Request.Cookies["userlroles"].Value == ""))    
                {
                    // 此时调用方法,访问数据库中的记录获得用户角色,并存入cookies
                    roles =(String[]) Users.GetRoles(User.Identity.Name).ToArray(typeof(String));
                    String roleStr = "";
                    foreach (String role in roles)     //一个用户会有多种角色,以一个字符串表示,用;隔开
                    {
                        roleStr += role;
                        roleStr += ";";
                    }

                    //创建cookies票据
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,                              //版本
                        Context.User.Identity.Name,     //登陆时候存入的标识用户的用户名
                        DateTime.Now,                   // 发布时间
                        DateTime.Now.AddHours(1),       // 过期时间
                        false,                          // 是否持久
                        roleStr                         // 角色字符串
                        );

                    // 加密票剧
                    String cookieStr = FormsAuthentication.Encrypt(ticket);
                    //发送到客户端,起名userroles
                    Response.Cookies["userroles"].Value = cookieStr;//必须加密
                    Response.Cookies["userroles"].Path = "/";
                    Response.Cookies["userroles"].Expires = DateTime.Now.AddMinutes(1);
                }

              else 
              {
                    // 已存在,读取,解密
         FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["userroles"].Value);
                    //把角色字符添加到list里
                 ArrayList userRoles = new ArrayList();
               foreach (String role in ticket.UserData.Split( new char[] {';'} )) 
               {
                    userRoles.Add(role);
                 }

                 roles = (String[]) userRoles.ToArray(typeof(String));
                }

                // 把此用户的角色存到内存中,可以运用User.IsInRole()方法进行检验用户角色
                // 也可以使用实现IPrincipal接口的类,自定义赋值给Context.User
                Context.User= new GenericPrincipal(Context.User.Identity, roles);
               }

        }

   4:然后添加读取验证用户是否存在的访问数据库代码,和获得用户角色的代码。
      详细码略,这里主要争对三张表写出获得用户角色的存储过程
    

CREATE PROCEDURE User_GetUserRolesByUsername 
(
    @Username  nvarchar( 50 )
)
AS
select Roles.RoleName
from Roles
join Users on Users.Username = @Username
join User_Role on User_Role.UserID = Users.UserID
where Roles.RoleID = User_Role.RoleID
GO

   至此,我们就完成了一般性的asp.net窗体验证的功能。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值