代码改变世界

Forms身份验证

2013-03-07 17:08  Carl Xing  阅读(382)  评论(0编辑  收藏  举报

Form身份验证需引入命名空间System.Web.Security。

配置web.config,在system.web节点下加上

      <authentication mode="Forms" >
        <forms loginUrl="Login.aspx" name=".FORMSAUTH"></forms>
      </authentication>
      <authorization>
        <deny users="?"/>
      </authorization>

也可在节点上添加账户:

<authentication mode="Forms" >
        <forms loginUrl="Login.aspx">
          <credentials passwordFormat="MD5">
            <user name="user" password="1A1DC91C907325C69271DDF0C944BC72"/>
          </credentials>
        </forms>
      </authentication>

用 if (FormsAuthentication.Authenticate(用户名, 密码))  可用来与web.config里配置的user对比以验证用户输入。

创建并添加forms身份验证的cookie,10秒钟后过期。这里的FormsCookieName就是配置文件中的.FORMSAUTH

            UserInfo user = new UserInfo() { Name = tbAccount.Text, Pwd = tbPwd.Text };
            string userData = user.Name + "|" + user.Pwd;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Name,
                DateTime.Now, DateTime.Now.AddSeconds(10), true, userData, FormsAuthentication.FormsCookiePath);
            string encTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            //cookie.Expires = DateTime.Now.AddSeconds(30);
            Response.Cookies.Add(cookie);

读取票据的cookie信息,先用FormsAuthentication.Decrypt来解密。如果是多服务器,这需要在system.web节点下添加machinekey节点。

如果多台服务器负载均衡,machineKey还采用动态生成的方式,每台服务器上的machinekey值不一致,就导致加密出来的结果也不一致,不能共享验证和ViewState,

所以对于多台服务器负载均衡的情况,一定要在每台站点配置相同的machineKey。

<machineKey validationKey="6E123429BC0534950B0920A7B59FA698BD02DSWS" decryptionKey="SWS850BB36319B474C996B506A95AEDF9B51211B1D4CEDFF" decryption="AES" validation="SHA1"/>