您的位置:首页 > 编程语言 > ASP

asp.net基于FORM的身份验证

2008-11-29 19:35 281 查看
using System;<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

using System.Web.Security;

using System.Security.Cryptography;

using System.Text;

using System.IO;

namespace CommandExample

{

     /// <summary>

     /// login 的摘要说明。

     /// </summary>

     public class Login01 : System.Web.UI.Page

     {

         protected System.Web.UI.WebControls.Label Label1;

         protected System.Web.UI.WebControls.TextBox tbName;

         protected System.Web.UI.WebControls.TextBox tbPass;

         protected System.Web.UI.WebControls.Button btnLoginBetter;

         protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;

         protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2;

         protected System.Web.UI.WebControls.CheckBox PersistCookie;

         protected System.Web.UI.WebControls.Label Label2;

    

         private void Page_Load(object sender, System.EventArgs e)

         {

              // 在此处放置用户代码以初始化页面

         }

 

         private void btnLoginBetter_Click(object sender, System.EventArgs e)

         {

              bool bExist = AuthenticateUser(tbName.Text,tbPass.Text);

              if(bExist)

              {

                   //1) //创建一个验证票据

                   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, tbName.Text,DateTime.Now,

                       DateTime.Now.AddMinutes(30),PersistCookie.Checked,"User");

                   //2) //并且加密票据

                   string cookieStr =  FormsAuthentication.Encrypt(ticket);

                //3) 创建cookie

                   HttpCookie cookie =new HttpCookie(FormsAuthentication.FormsCookieName,cookieStr);

                   if(PersistCookie.Checked) //如果用户选择了保存密码

                       cookie.Expires=ticket.Expiration;//设置cookie有效期

                   //cookie存放路径

                   cookie.Path = FormsAuthentication.FormsCookiePath;

                Response.Cookies.Add(cookie);

                   // 4) do a redirect

                   string strRedirect;

                   strRedirect=Request["ReturnUrl"];

                   if(strRedirect==null)

                       strRedirect="default.aspx";

                   Response.Redirect(strRedirect,true);

              }

              else

                   Response.Write("<script language='javascript'>alert('用户名称或密码错误!')</script>");

             

         }

         private bool ArraysEqual(byte[] array1,byte[] array2)

         {

              bool bResult = true;

              if(array1==null)

                   throw new ArgumentNullException("array1");

              if(array2==null)

                   throw new ArgumentNullException("array2");

              if(array1.Length == array2.Length)

              {

                   for(int i=0;i<array1.Length;i++)

                   {

                       if(array1[i]!=array2[i])

                       {

                            bResult = false;

                            break;

                       }

                   }

              }

 

              return bResult;

         }

         private bool AuthenticateUser(string strUserName, string strUserPass)

         {

              SqlConnection con = new SqlConnection();

              con.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["DSN"];

              con.Open();

        

              string strSql = "sp_getuserdetails";

              SqlCommand com = new SqlCommand(strSql,con);

              com.CommandType = CommandType.StoredProcedure;

              SqlParameter sqlpUser = new SqlParameter("@acctname",SqlDbType.NVarChar,64);

              sqlpUser.Value = tbName.Text;

              SqlParameter sqlpPasshash = new SqlParameter("@passhash",SqlDbType.NVarChar,50);

              sqlpPasshash.Direction = ParameterDirection.Output;

              SqlParameter sqlpPasssalt = new SqlParameter("@passsalt",SqlDbType.NVarChar,50);

              sqlpPasssalt.Direction = ParameterDirection.Output;

              com.Parameters.Add(sqlpUser);

              com.Parameters.Add(sqlpPasssalt);

              com.Parameters.Add(sqlpPasshash);

              com.ExecuteNonQuery();

 

              string hash = com.Parameters["@passhash"].Value.ToString();

              string salt = com.Parameters["@passsalt"].Value.ToString();

 

              bool bExist = false;

              if(hash==null||salt==null)

                   bExist = false;

              else

              {

                   byte[] saltBits = Convert.FromBase64String(salt);

                   byte[] hashBits = Convert.FromBase64String(hash);

                   byte[] passBits = Encoding.Unicode.GetBytes(strUserPass);

                  

                   HashAlgorithm hashAlg = SHA1.Create();

                   CryptoStream cs = new CryptoStream(Stream.Null,hashAlg,CryptoStreamMode.Write);

                   cs.Write(passBits,0,passBits.Length);

                   cs.Write(saltBits,0,saltBits.Length);

                   cs.FlushFinalBlock();

                   cs.Close();

 

                   byte[] digest = hashAlg.Hash;

                   if (ArraysEqual(digest,hashBits))

                       bExist = true;

                   else

                       bExist = false;

              }

              con.Close();

              return bExist;

         }

 

     }

}

 

 

 

FormsAuthentication类:为 Web 应用程序管理 Forms 身份验证服务

方法

名称
说明
Authenticate
对照存储在应用程序配置文件中的凭据来验证用户名和密码。
GetAuthCookie
已重载。 为给定的用户名创建身份验证 Cookie。
GetRedirectUrl
返回导致重定向到登录页的原始请求的重定向 URL。
Initialize
根据应用程序的配置设置初始化 FormsAuthentication 对象。
RedirectToLoginPage
已重载。 将浏览器重定向到登录 URL。
RenewTicketIfOld
有条件地更新 FormsAuthenticationTicket 的发出日期和时间以及过期日期和时间。
SetAuthCookie
为提供的用户名创建一个身份验证票证,并将其添加到响应的 Cookie 集合或 URL。
SignOut
从浏览器删除 Forms 身份验证票证。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息