10/11/2013
4:28:00 PM 0

HTTP basic access authentication

HTTP basic access authentication 是一個很基本的認證方式, 安全性差, 採用 Base64 編碼傳送帳號密碼

認證流程

1.瀏覽器對 Server 端發出請求

2.Server 端檢查該 User 尚未認證, 回應 Status Code 401 和 WWW-Authenticate 資訊在 header 中, 告訴瀏覽器需做基本認證

HTTP/1.0 401 Unauthorised
Content-Type: text/html; charset=UTF-8
WWW-Authenticate: Basic realm="TestSite"
Connection: Close
Content-Length: 24

3.使用者在瀏覽器畫面鍵入 User Name 和 Password 送出請求, 送出的 header 中, 接續在 Authorization: Basic 之後的文字, 就是帳號和密碼的 Base64 編碼

GET / HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Authorization: Basic QWRDSpc3RyYXRVVVVSU=

4.Server 端認證成功則回應 Status Code 200, 若認證失敗, 則回到步驟 2

HTTP/1.0 200 OK
Content-Type: text/html; charset=UTF-8
Connection: Keep-Alive
Content-Length: 989

有些 Server 在認證失敗時, 會修改 Status Code 401 的訊息, Reason Phrase 會因 Server 實作而有所不同

HTTP/1.0 401 Invalid credentials
Content-Type: text/html; charset=UTF-8
WWW-Authenticate: Basic realm="TestSite"
Connection: Close
Content-Length: 0

5.若使用者在認證視窗按下取消按鈕, 同樣回應 Status Code 401, 但 Reason Phrase 改為 Access Denied, 訊息部分會因 Server 實作而有所不同

HTTP/1.0 401 Access Denied
Content-Type: text/html; charset=UTF-8
WWW-Authenticate: Basic realm="TestSite"
Connection: Close
Content-Length: 24

HTTP 協定允許自定 Reason Phrase, 詳細可參考 http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1

使用C#程式做自動認證登入
String userName = "Administrator";
String password = "password";
String header = "Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + password)) + System.Environment.NewLine;

webBrowser.Navigate(String.Format("http://{0}:{1}@127.0.0.1", userName, password), null, null, header);

0 comments:

Post a Comment