2011-02-27 157 views
5

我有一個期望soap頭部並返回身份驗證令牌的Webservice。我設法使用jQuery將soap頭文件發佈到webservice。問題是如何使瀏覽器在每個Web服務授權請求上發送經過身份驗證的令牌。你的幫助將會很受歡迎。我用有用的鏈接如下: 參考:使用jQuery通過web服務進行SOAP身份驗證

  1. Securing ASP.Net Web Service using SOAP

  2. Calling Webservice from Jquery (Posting SOAP Header)

代碼:

function logIn(username, password, token) { 
     var soapMessage = 
     '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \ 
     <soap:Body> \ 
     <SecuredWebServiceHeader xmlns="http://tempuri.org/"> \ 
     <Username>' + username + '</Username> \ 
     <Password>' + password + '</Password> \ 
     <AuthenticatedToken>' + token + '</AuthenticatedToken> \ 
     </SecuredWebServiceHeader> \ 
     </soap:Body> \ 
     </soap:Envelope>'; 

     $.ajax({ 
      url: "http://localhost/wstest/Service.asmx/AuthenticateUser", 
      type: "POST", 
      dataType: "xml", 
      data: soapMessage, 
      complete: endLogin, 
      contentType: "text/xml; charset=\"utf-8\"" 
     }); 

     return false; 
    } 

    function endLogin(xmlHttpRequest, status) { 
     alert(xmlHttpRequest.responseXML) 
    } 

回答

0

如果響應提供了一個積極的 - 發送令牌返回到您的服務器進行存儲在會議中。

0

我有同樣的情況,必須使用表單認證保護我的網站(包括網絡服務)的一部分,並且還有一個未受保護的公共部分,例如,登錄/註冊表單,CSS文件,JS文件...

我通過指定可以處理您的登錄功能的公共Web服務(不受表單身份驗證保護)來解決登錄問題。

你的登錄功能,應該是這樣的:

[WebMethod(EnableSession=true)] 
[ScriptMethod] 
public ResponseBase<bool> DoLogin(LoginCredentials Credentials) 
{ 
     try 
     { 
      // Perform login with credentials 

      if (loginOK) 
      { 
       FormsAuthentication.SetAuthCookie(/* Your user identification here */, true); 
      } 
      return new ResponseBase<bool> { Code= true}; 
     } 
     catch (Exception _ex) 
     { 
      // Save your log 
      return new ResponseBase<bool> { Message = "Incorrect Login" }; 
     } 
} 

您的客戶端將收到的窗體身份驗證cookie並登錄你的迴應。稍後,您可以通過評估響應中的代碼屬性來評估登錄是否成功。

的ResponseBase的類如下所示:

[Serializable] 
[DataContract] 
public class ResponseBase<T> 
{ 
    /// <summary> 
    /// Return code. 
    /// </summary> 
    [DataMember] 
    public T Code { get; set; } 

    /// <summary> 
    /// Message. 
    /// </summary> 
    [DataMember] 
    public string Message { get; set; } 
} 

最後,但並非最不重要的,我建議你使用的不是XML JSON在零個改變通話,因爲消息的重量輕的您的Web服務服務器代碼。此外,在客戶端中,您不必手動構建消息,就像在您的示例中一樣。

相關問題