首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 模擬網站用戶登入:HttpWebRequest 處理 Cookie、Session 與多步驟驗證流程

     編輯:關於C#

HTTP 無狀態與 Session 機制

伺服器建立 Session 物件,以 SessionID 識別用戶。首次回應透過 Set-Cookie 標頭將 SessionID 送至瀏覽器,後續請求自動攜帶 Cookie。

抓包分析流程(以盛大縱橫天下為例)

  1. 清除 IE Cookie,啟動 HTTP Analyzer。
  2. 瀏覽 https://cas.sdo.com/cas/login?service=... → 取得 ASP.NET_SessionId。
  3. 頁面含 lt (ticket) 參數:location.href = login2.asp?lt=xxx&service=...
  4. POST lt、帳號、密碼至 Login.PostTarget.aspx。
  5. 驗證成功後存取受保護頁面確認登入狀態。

核心程式碼封裝


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");
    }
}

關鍵技術點

  • CookieContainer:自動管理跨請求 Cookie,維持 Session。
  • HttpWebRequest/Response:.NET 高層 HTTP 客戶端,支援 Keep-Alive、重導向、憑證。
  • 流程自動化:抓包→分析參數→程式碼重現請求序列。
  • 錯誤處理:網路例外、重導向循環、驗證碼、雙因子認證等實務挑戰需額外處理。

後續操作

登入成功後,所有受保護 API 僅需攜帶相同 CookieContainer 發送請求即可。灌水、下載資源等同理:在瀏覽器操作一次、抓包、用 C# 重現封包。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved