萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 以 Forms Authentication 保護 Web Service 實作完整教學

傳統 ASMX Web Service 若需身分驗證,常見做法為自訂 SOAP Header 或輸入參數驗證。本文示範如何將既有的 Forms Authentication (Cookie-based) 延伸至 Web Service,讓用戶登入網站後即可直接呼叫受保護的 Web Service,無需額外驗證邏輯。關鍵在於 客戶端代理類共用 CookieContainer 以及 登入入口點暴露為 Web Service 方法。

架構圖解

Browser (User) --登入頁--> Login.aspx (Forms Auth) --設定 Cookie--> 
Client App (WinForms/WPF/Console) --呼叫 Login.asmx/Check()--> 取得 Cookie --> 
Client App --攜帶 Cookie 呼叫 SecureService.asmx/DoWork()-->

Web.config 設定

<system.web>
  <authentication mode="Forms">
    <forms name="MyServiceAuth" loginUrl="Login.asmx" timeout="60" />
  </authentication>
  <authorization>
    <deny users="?" /> <!-- 禁止匿名 -->
  </authorization>
</system.web>

<!-- 允許匿名存取登入服務 -->
<location path="Login.asmx">
  <system.web>
    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>
</location>

登入 Web Service (Login.asmx)

[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Login : WebService {
    [WebMethod(EnableSession = true)]
    public bool Check(string userName, string password) {
        // 實際應驗證資料庫/Identity
        if (ValidateUser(userName, password)) {
            FormsAuthentication.SetAuthCookie(userName, false); // 寫入 Cookie
            return true;
        }
        return false;
    }
    private bool ValidateUser(string u, string p) => u == "admin" && p == "123456"; // Demo
}

受保護的業務 Web Service (SecureService.asmx)

[WebService(Namespace = "https://tempuri.org/")]
public class SecureService : WebService {
    [WebMethod(EnableSession = true)]
    public string DoWork() {
        // Context.User.Identity 已由 FormsAuthenticationModule 自動填入
        if (Context.User.Identity.IsAuthenticated) {
            return $"Hello, {Context.User.Identity.Name}! 當前時間: {DateTime.Now}";
        }
        throw new UnauthorizedAccessException("未驗證");
    }
}

客戶端呼叫範例 (WinForms / Console)

class Program {
    static CookieContainer _cookieJar = new CookieContainer();

    static void Main() {
        Login();      // 1. 登入取得 Cookie
        CallService(); // 2. 攜帶 Cookie 呼叫受保護服務
        Console.ReadKey();
    }

    static void Login() {
        var loginSvc = new LoginServiceReference.Login();
        loginSvc.CookieContainer = _cookieJar;
        bool ok = loginSvc.Check("admin", "123456");
        Console.WriteLine($"登入 {(ok ? "成功" : "失敗")}");
    }

    static void CallService() {
        var svc = new SecureServiceReference.SecureService();
        svc.CookieContainer = _cookieJar; // 關鍵:共用同一 CookieContainer
        try {
            string result = svc.DoWork();
            Console.WriteLine($"服務回應: {result}");
        } catch (SoapException ex) {
            Console.WriteLine($"錯誤: {ex.Message}");
        }
    }
}

關鍵細節與避坑指南

  1. EnableSession=true:ASMX 預設不啟用 Session,需在 [WebMethod(EnableSession=true)] 開啟,否則無法讀寫 Cookie/Session。
  2. CookieContainer 共用:客戶端必須對所有服務代理類指派**同一個** CookieContainer 實例,才能維持跨服務的身分。
  3. loginUrl 設為 .asmx:讓未驗證請求導向登入服務而非 .aspx 頁面,避免機器對機器 (A2A) 場景出現 HTML 重導向。
  4. 授權屬性:<deny users="?" /> 保護所有 .asmx,再以 <location> 開放 Login.asmx 匿名存取。
  5. 安全性補強:生產環境必須強制 HTTPS,否則 Cookie 明文傳輸極易被竊聽;考慮將票據加密 (protection="All") 並設定 requireSSL="true"。

適用場景與限制

  • ✅ 內部系統整合、WinForms/WPF 桌面應用呼叫 ASMX、舊專案快速加入驗證。
  • ❌ 跨網域/行動裝置/第三方整合:建議改用 Token (JWT/OAuth2) 或 ASP.NET Core Web API + IdentityServer。
  • ❌ 高併發/無狀態微服務:Forms Auth 依賴伺服器端 Session/票據,不利水平擴展。

此模式讓傳統 ASMX 以最低成本獲得 Forms Authentication 保護,適合漸進式現代化遷移前的過渡方案。

copyright © 萬盛學電腦網 all rights reserved