傳統 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()-->
<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>
[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
}
[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("未驗證");
}
}
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}");
}
}
}
[WebMethod(EnableSession=true)] 開啟,否則無法讀寫 Cookie/Session。CookieContainer 實例,才能維持跨服務的身分。<deny users="?" /> 保護所有 .asmx,再以 <location> 開放 Login.asmx 匿名存取。protection="All") 並設定 requireSSL="true"。此模式讓傳統 ASMX 以最低成本獲得 Forms Authentication 保護,適合漸進式現代化遷移前的過渡方案。