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

ASP.NET Forms 認證應用於 Web Service:跨應用程式身份驗證完整方案

     編輯:關於ASP.NET

ASP.NET Forms 認證基於 Cookie,預設適用於瀏覽器場景。若要在 Web Service (A2A) 客戶端程式中複用 Forms 認證,需解決兩大難題:

  1. Cookie 容器管理:Web Service Proxy 預設不自動儲存/發送 Cookie。
  2. 避免人機交互登入頁:Web Service 不適合導向 HTML 登入表單。

方案架構

建立專用登入 Web Service Login.asmx,將 web.config 中 forms loginUrl 指向它,並允許匿名存取該服務。客戶端程式先呼叫 Login.asmx 取得認證 Cookie,再攜帶 Cookie 呼叫業務 Web Service。

關鍵配置 (web.config)

<authentication mode="Forms">
  <forms name="MyService" loginUrl="Login.asmx" />
</authentication>
<authorization>
  <deny users="?" />
</authorization>

登入 Web Service 實作

[WebMethod]
public bool Check(string userName, string password)
{
    if (userName == "aaaaaa" && password == "123456") // 實際應對接 Membership/資料庫
    {
        FormsAuthentication.SetAuthCookie(userName, false);
        return true;
    }
    return false;
}

客戶端程式碼 (WinForm/Console)

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 認證無縫延伸至機器對機器調用,保持單一認證體系,降低維護成本。

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