經典 ASP (VBScript) + SQL Server 登入驗證,**必須使用參數化查詢** 防止 SQL 注入,驗證通過後寫入 Session。
<%
' 1. 取得表單輸入
Dim username, password
username = Request.Form("username")
password = Request.Form("password")
If username = "" Or password = "" Then
Response.Write "帳號密碼不可為空"
Response.End
End If
' 2. 參數化查詢 (ADODB.Command)
Dim conn, cmd, rs
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=.;Initial Catalog=MyDB;User Id=sa;Password=your_pwd;"
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = conn
cmd.CommandText = "SELECT user_id, username, role FROM users WHERE username = ? AND pwd_hash = HASHBYTES('SHA2_256', ?)"
cmd.CommandType = 1 ' adCmdText
cmd.Parameters.Append cmd.CreateParameter("@username", 200, 1, 50, username) ' adVarChar, adParamInput
cmd.Parameters.Append cmd.CreateParameter("@password", 200, 1, 50, password)
Set rs = cmd.Execute
' 3. 驗證結果
If Not rs.EOF Then
' 登入成功,寫入 Session
Session("user_id") = rs("user_id")
Session("username") = rs("username")
Session("role") = rs("role")
Session.Timeout = 30 ' 分鐘
Response.Redirect "main.asp"
Else
Response.Write "帳號或密碼錯誤"
End If
' 4. 清理資源
rs.Close: Set rs = Nothing
cmd.ActiveConnection = Nothing: Set cmd = Nothing
conn.Close: Set conn = Nothing
%>
| 風險 | 錯誤做法 | 正確做法 |
|---|---|---|
| SQL 注入 | `sql = "SELECT * FROM users WHERE u='" & username & "' AND p='" & password & "'"` | 參數化查詢 `?` + `Command.Parameters` |
| 明文密碼 | 資料庫存 `password` 明文 | 存 `HASHBYTES('SHA2_256', password)` 或應用層 bcrypt |
| Session 劫持 | 無 HTTPS、SessionID 暴露 | 全站 HTTPS、HttpOnly Cookie、定期換 SessionID |
| 暴力破解 | 無限制嘗試 | IP/帳號失敗計數、驗證碼、帳號鎖定 |
<%
If Session("user_id") = "" Then
Response.Redirect "login.asp?returnUrl=" & Server.URLEncode(Request.ServerVariables("URL"))
Response.End
End If
%>
參數化查詢是底線,Session 管理是基線,安全意識是生命線。