WCF身份驗證服務


WCF身份驗證服務

Windows Communication Foundation (WCF) 身份驗證服務使你能夠使用ASP.NET成員資格,從可以發送和使用SOAP消息的任何應用程序中對用戶進行身份驗證。這可以包括不使用.NET Framework的應用程序。因此,這些不同的應用程序的用戶不需要對每個應用程序使用單獨的憑據。用戶在使用任意客戶端應用程序時,均可通過提供相同的憑據登錄到應用程序中。本節就使用WCF身份驗證服務的幾個關鍵點做實踐性分析。

創建WCF身份驗證服務

System.Web.ApplicationServices.AuthenticationService.NET提供的默認身份驗證服務類。AuthenticationService類包含只應通過WCF服務訪問的四個方法:IsLoggedInLoginLogout ValidateUser方法。若要調用這些方法,請啟用Web服務器上的身份驗證服務,然后將WCF兼容的客戶端應用程序連接到Web服務。

若要使用戶登錄,請將用戶憑據傳遞給Login方法。如果憑據有效,AuthenticationService類創建一個身份驗證Cookie如果身份驗證Cookie尚未過期,並且知道該用戶的憑據已經過身份驗證,則不必再次驗證憑據。

注意 不能通過AuthenticationService類使用無Cookie身份驗證。

AuthenticationService可引發兩個事件:AuthenticatingCreatingCookie。當驗證用戶憑據時發生Authenticating事件。為Authenticating事件創建一個事件處理程序以自定義如何驗證用戶憑據。在驗證完用戶憑據后設置身份驗證Cookie時發生CreatingCookie事件。CreatingCookie事件創建一個事件處理程序以自定義身份驗證Cookie

ValidateUser方法檢查用於身份驗證的用戶憑據,但該方法不返回身份驗證票證。當用戶先前已登錄且必須檢查憑據在新的應用程序會話開始時是否仍然有效時,請使用ValidateUser方法。

現在新建一個.svc文件,如果使用默認的System.Web.ApplicationServices.AuthenticationService類提供成員資格驗證服務,可以刪除默認生成的接口文件和類文件,然后修改.svc文件,修改后的內容如下所示:

<%@ ServiceHost Language="C#"

Service="System.Web.ApplicationServices.ProfileService"

%>

如果要實現自定義的成員資格服務,只需要為Authenticating事件創建一個事件處理程序即可。

首先,創建如代碼清單10-28所示的Authenticating事件處理程序。

代碼清單10-28  Authenticating事件處理程序

void AuthenticationService_Authenticating(object sender, System.Web.ApplicationServices.AuthenticatingEventArgs e)

{

    if (e.UserName.IndexOf("@xuanhun.com") >= 0)

    {

        e.Authenticated = Membership.Providers["xuanhunSqlProvider"].ValidateUser(e.UserName, e.Password);

    }

    elseif (e.UserName.IndexOf("@xuanbing.com") >= 0)

    {

        e.Authenticated = Membership.Providers["xuanbingSqlProvider"].ValidateUser(e.UserName, e.Password);

    }

    else

    {

        e.Authenticated = Membership.Provider.ValidateUser(e.UserName, e.Password);

    }

    e.AuthenticationIsComplete = true;

}

以上代碼所示的Authenticating事件處理程序中,使用三個成員資格提供程序來驗證用戶,分別是自定義的xuanbingSqlProviderxuanhunSqlProvider和配置文件中配置的默認的成員資格提供程序。驗證之后設置當前用戶的驗證狀態。

在編寫完Authenticating事件處理程序后,需要在Global.asax文件的Application_Start方法中綁定Authenticating事件的處理程序。代碼如下所示:

void Application_Start(object sender, EventArgs e)

{

    System.Web.ApplicationServices.AuthenticationService.Authenticating +=

        new EventHandler<System.Web.ApplicationServices.AuthenticatingEventArgs>(AuthenticationService_Authenticating);

}

 

啟用身份驗證服務

 

若要使上面創建的服務生效,必須在配置文件中做相關的配置。如何配置WCF服務的細節這里不做講解,請參考相關WCF開發資料。

configSections元素和appSettings元素之間添加一個新的system.web.extensions元素,然后向system.web.extensions元素中添加一個scripting元素,在scripting元素中,通過webServices節啟用身份驗證、配置文件和角色服務。代碼清單10-29給出了一個簡單的配置示例。

代碼清單10-29   配置身份驗證服務

<system.web.extensions>

  <scripting>

    <webServices>

      <authenticationService enabled="true"

         requireSSL = "true"/>

    </webServices>

  </scripting>

</system.web.extensions>

<system.serviceModel>

  <services>

    <service name="System.Web.ApplicationServices.AuthenticationService"

behaviorConfiguration="AuthenticationServiceTypeBehaviors">

      <endpoint contract=

        "System.Web.ApplicationServices.AuthenticationService"

        binding="basicHttpBinding"

        bindingConfiguration="userHttps"

bindingNamespace="http://xuanhun.net/ApplicationServices/membership"/>

      </service>

  </services>

  <bindings>

        <basicHttpBinding>

            <binding name="userHttps">

                <security mode="Transport" />

            </binding>

        </basicHttpBinding>

  </bindings>

  <behaviors>

    <serviceBehaviors>

      <behavior name="AuthenticationServiceTypeBehaviors">

        <serviceMetadata httpGetEnabled="true"/>

      </behavior>

    </serviceBehaviors>

  </behaviors>

  <serviceHostingEnvironment

    aspNetCompatibilityEnabled="true"/>

</system.serviceModel>

在代碼清單10-29的配置中,首先通過設置<authenticationService enabled="true" requireSSL = "true"/>來啟用身份驗證服務,並要求通過SSL來通信。之后services元素中定義終結點協定,在 behaviors 元素中定義服務行為。在配置文件的最后,serviceHostingEnvironment配置節中設置aspNetCompatibilityEnabled="true",該配置用來指示在應用程序中運行的所有WCF服務在 ASP.NET兼容模式中運行。除了上面的配置之外,還必須為ASP.NET應用啟用Forms身份驗證。此時可以使用默認的或者自定義的驗證程序來驗證用戶信息了。

自定義身份驗證Cookie

身份驗證服務將在已驗證用戶憑據之后且在已設置身份驗證Cookie之前引發CreatingCookie事件。通過為CreatingCookie創建事件處理程序並自行管理身份驗證Cookie,可以自定義Cookie通過傳遞給事件處理程序的CreatingCookieEventArgs對象可以訪問用戶名、密碼和自定義憑據。代碼清單10-30CreatingCookie事件創建事件處理程序的示例。

代碼清單10-30   CreatingCookie事件處理程序

void AuthenticationService_CreatingCookie(object sender,

    System.Web.ApplicationServices.CreatingCookieEventArgs e)

{

    FormsAuthenticationTicket ticket = new

          FormsAuthenticationTicket

            (1,

             e.UserName,

             DateTime.Now,

             DateTime.Now.AddMinutes(30),

             e.IsPersistent,

             e.CustomCredential,

             FormsAuthentication.FormsCookiePath);

 

    string encryptedTicket =

         FormsAuthentication.Encrypt(ticket);

 

    HttpCookie cookie = new HttpCookie

         (FormsAuthentication.FormsCookieName,

          encryptedTicket);

    cookie.Expires = DateTime.Now.AddMinutes(30);

 

    HttpContext.Current.Response.Cookies.Add(cookie);

    e.CookieIsSet = true;

}

在代碼清單10-30中,通過將CustomCredential屬性的值添加到UserData屬性來自定義身份驗證Cookie

下面在Global.asax文件的Application_Start方法中,綁定CreatingCookie事件的處理程序,代碼如下所示:

void Application_Start(object sender, EventArgs e)

{

    System.Web.ApplicationServices.AuthenticationService.CreatingCookie

        += new EventHandler<System.Web.ApplicationServices.CreatingCookieEventArgs>

        (AuthenticationService_CreatingCookie);

}

經過了上面的代碼編寫和配置,現在可以使用WCF服務來完成身份驗證了。

 ---------------------------------------------------注:本文部分內容改編自《.NET 安全揭秘》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM