本文提供一個最基礎的 ASP.NET 登入範例,供初學者理解流程。**注意:此代碼存在 SQL 注入風險、明文密碼、硬編碼連線字串等安全問題,嚴禁用於生產環境。**
string conn = "server=.;database=login;user id=sa;pwd=123";
SqlConnection cn = new SqlConnection(conn);
cn.Open();
string strsql = "select user_name,user_pwd from admin where user_name='" + TextBox1.Text + "' or user_pwd='" + TextBox2.Text + "'";
SqlCommand cmd = new SqlCommand(strsql, cn);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
if (rd.GetValue(0).ToString() == TextBox1.Text)
{
if (rd.GetValue(1).ToString() == TextBox2.Text)
{
Response.Redirect("Default.aspx");
}
else { Response.Write("<script>alert('密碼錯誤!')</script>"); }
}
else { Response.Write("<script>alert('用戶名錯誤!')</script>"); }
}
else { Response.Write("<script>alert('用戶不存在!')</script>"); }
| 問題 | 風險 | 改進建議 |
|---|---|---|
| 字串拼接 SQL | SQL 注入 | 使用參數化查詢 @user_name |
| 明文儲存/比對密碼 | 資料外洩即洩露密碼 | 儲存 BCrypt/Argon2 雜湊,驗證時比對雜湊 |
| 硬編碼連線字串 | 部署困難、洩露帳密 | 放入 web.config connectionStrings,生產環境加密 |
| 邏輯混雜於事件處理 | 難以測試、維護 | 分層:UI → BLL (驗證邏輯) → DAL (資料存取) |
使用 sa 高權限帳號 | 資料庫完全失控 | 建立最小權限應用程式帳號 |
// BLL
public bool ValidateUser(string userName, string password)
{
const string sql = "SELECT pwd_hash FROM Users WHERE user_name = @u";
using (var cn = new SqlConnection(connStr))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.AddWithValue("@u", userName);
cn.Open();
var hash = cmd.ExecuteScalar() as string;
return hash != null && BCrypt.Net.BCrypt.Verify(password, hash);
}
}
入門階段可先跑通流程,但請盡快建立安全編碼習慣,改用參數化查詢、密碼雜湊、分層架構與 ASP.NET Identity / Membership 等成熟框架。