ASP.NET Forms 認證基於 Cookie,預設適用於瀏覽器場景。若要在 Web Service (A2A) 客戶端程式中複用 Forms 認證,需解決兩大難題:
建立專用登入 Web Service Login.asmx,將 web.config 中 forms loginUrl 指向它,並允許匿名存取該服務。客戶端程式先呼叫 Login.asmx 取得認證 Cookie,再攜帶 Cookie 呼叫業務 Web Service。
<authentication mode="Forms"> <forms name="MyService" loginUrl="Login.asmx" /> </authentication> <authorization> <deny users="?" /> </authorization>
[WebMethod]
public bool Check(string userName, string password)
{
if (userName == "aaaaaa" && password == "123456") // 實際應對接 Membership/資料庫
{
FormsAuthentication.SetAuthCookie(userName, false);
return true;
}
return false;
}
class Sample
{
CookieContainer cookieContainer = new CookieContainer();
public void Login()
{
MyServiceLogin.Login login = new MyServiceLogin.Login();
login.CookieContainer = cookieContainer;
login.Check("aaaaaa", "123456");
}
public void ShowHelloWorld()
{
MyService.WebService service = new MyService.WebService();
service.CookieContainer = cookieContainer; // 共享 Cookie
Console.WriteLine(service.HelloWorld());
}
}
CookieContainer 實例在登入與業務 Proxy 間共享。loginUrl 指向 .asmx 而非 .aspx,避免 HTML 表單導向。<deny users="?"/> 確保未認證請求被攔截並導向 Login.asmx。此方案讓傳統 Forms 認證無縫延伸至機器對機器調用,保持單一認證體系,降低維護成本。