伺服器建立 Session 物件,以 SessionID 識別用戶。首次回應透過 Set-Cookie 標頭將 SessionID 送至瀏覽器,後續請求自動攜帶 Cookie。
https://cas.sdo.com/cas/login?service=... → 取得 ASP.NET_SessionId。lt (ticket) 參數:location.href = login2.asp?lt=xxx&service=...lt、帳號、密碼至 Login.PostTarget.aspx。
using System;
using System.IO;
using System.Net;
using System.Text;
public class WebAuth
{
private CookieContainer _cookies = new CookieContainer();
// 取得頁面 HTML
public string GetHtml(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = _cookies;
req.Credentials = CredentialCache.DefaultCredentials;
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default))
return sr.ReadToEnd();
}
// POST 表單資料
public string PostData(string url, string postData)
{
byte[] data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.CookieContainer = _cookies;
using (Stream st = req.GetRequestStream()) st.Write(data, 0, data.Length);
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default))
return sr.ReadToEnd();
}
// 解析 HTML 取得 lt 值(簡易示範,實務建議用 HtmlAgilityPack)
private string ExtractLt(string html)
{
int idx = html.IndexOf("lt=");
if (idx < 0) return null;
idx += 3;
int end = html.IndexOf('&', idx);
return end > 0 ? html.Substring(idx, end - idx) : html.Substring(idx);
}
// 完整登入流程
public bool Login(string user, string pwd)
{
// 1. 取得初始頁面與 Session
string html = GetHtml("https://cas.sdo.com/cas/login?service=https://zh.sdo.com/web1.0/home/fastlogin.asp");
// 2. 解析 lt
string lt = ExtractLt(html);
if (lt == null) return false;
// 3. POST 登入
string post = $"warn=false&_eventId=submit&idtype=0&gamearea=0&gametype=0&challenge=3623<={lt}&username={user}&password={pwd}&ekey=";
string result = PostData("https://cas.sdo.com:80/cas/Login.PostTarget.aspx?service=https://zh.sdo.com/web1.0/home/fastlogin_after.asp", post);
// 4. 驗證是否成功(檢查重導向或特定關鍵字)
return result.Contains("登入成功") || result.Contains("welcome");
}
}
登入成功後,所有受保護 API 僅需攜帶相同 CookieContainer 發送請求即可。灌水、下載資源等同理:在瀏覽器操作一次、抓包、用 C# 重現封包。