蛙蛙推薦:asp.net中的身分識別驗證
我用的是基於表單的驗證,這也是最常用的,我唯寫一下摘要,原始碼太長,但應該不影響理解代碼.
web.config的修改:
<authentication mode="Forms" />
使用者的登陸驗證方法,:
這裡有兩個輸入控制項的,一個是user_tb,用來輸入使用者,一個是psw_tb,用來輸入密碼
private void Button1_Click(object sender, System.EventArgs e)
{
//使用者登陸驗證
string ip= System.Web.HttpContext.Current.Request.UserHostAddress ;
string user_name=user_tb.Text;
string user_psw=psw_tb.Text;
user_name=user_name.Replace("<","<").Replace(">",">").Replace(" "," ").Replace("'","‘");
user_psw=user_psw.Replace("<","<").Replace(">",">").Replace(" "," ").Replace("'","‘");
if(user_name!=""||user_psw!="")
{
SqlConnection myconn=new
SqlConnection((string)ConfigurationSettings.AppSettings["connstring"]);//串連資料庫
myconn.Open();//開啟
string validate_Sql="select * from Web_User where User_Name='"+user_name+"'and
User_Psw='"+user_psw+"'";
SqlCommand validate_com=new SqlCommand(validate_Sql,myconn);
SqlDataReader validate=validate_com.ExecuteReader();
string temp="";
while(validate.Read())
{
Session["user_name"]=user_name;
Session["user_flag"]=validate["User_Flag"].ToString();
temp="yes";
}
validate.Close();
if(temp=="yes")
{
user_tb.Text="";
psw_tb.Text="";
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(user_name,false);
Response.Redirect("manage_index.aspx");
}
else
{
Response.Write("<s cript>alert('您的使用者名稱或密碼錯誤!');</script>");
return ;
}
user_tb.Text="";
psw_tb.Text="";
myconn.Close();
}
}
判斷使用者是否已經登陸:
private void Page_Load(object sender, System.EventArgs e)
{
//在這裡判斷使用者是否已經登陸
if(!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
Response.Write("< script>alert('您沒有登陸!');history.back()</script>");
}
string strUsername;
strUsername=System.Web.HttpContext.Current.User.Identity.Name+"<br>+System.Web.HttpContext.Current.User.Identity.IsAuthentica
ted";
lbIUsername.Text=strUsername;
// 在此處放置使用者代碼以初始化頁面
}
使用者的退出:
private void LinkButton1_Click(object sender, System.EventArgs e)
{ //退出
Session["user_name"]=null;
Session["user_flag"]=null;
Session.Clear();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("default.aspx");
}
補充:
我首先發現My Code有幾個不足的地方
首先這句不必要,因為password是不會被viewstate的
psw_tb.Text="";
其次我的sql執行語句是動態構建的字串,其實正確的做法應該使用參數話查詢,雖然我替換了單引號,單也不能防止別人用8進位來進行sql注
入攻擊;
還有就是這句
Response.Redirect("manage_index.aspx");
其實不應該在這裡轉向的,要想設定預設登陸頁應該在web.config裡設定
FormsAuthentication.RedirectFromLoginPage(user_name,false);
是指登陸後自動轉向到你先前想要訪問的頁面,如果想制定轉向頁的話也不應該用Response.Redirect,而應該重寫那個類;
還有就是我這個驗證類是用票據和session同時驗證的,這樣做也不是很好,如果想維持使用者權限,email等多個欄位的話應該重寫使用者驗證票據,
而不是用session來維持,我這裡是偷懶了,呵呵