2010-08-12 136 views
3

我正在調用ASP.NET 2.0網站的.NET 2.0 winforms應用程序。該網站使用表單身份驗證進行身份驗證。身份驗證服務在web.config中啓用,並且我已完成一些experiments以確認我可以通過JSON訪問該服務。從非Web客戶端調用ASP.NET 2.0身份驗證服務

這裏是我的問題:是否有任何內置代碼在純.NET環境(而不是ASP.NET)中使用System.Web.Extensions Web服務(authenticationService,profileService等)?我可以找到使用Silverlight和更高版本的WCF服務的示例,但在客戶端和服務器上都沒有2.0環境中的任何示例。將身份驗證服務添加爲Web服務似乎是合乎邏輯的方法,但我永遠無法將它指向我的開發服務器 - 我想這可能是一個單獨的問題。

如果我必須在較低的級別管理AJAX請求和響應,那肯定是可行的,但如果已經有這樣的目的,它肯定會更容易,更不容易出錯。

回答

1

我從來沒有得到答案,但最終在this tutorial的幫助下找到了答案。簡短回答是肯定的,我必須在相當低的水平上管理AJAX請求/響應。假設你有一個你需要認證的用戶名和密碼,你首先需要得到一個認證cookie。我使用Json.NET library from Newtonsoft進行JSON序列化和反序列化,但您可以使用任何東西。

Cookie GetFormAuthenticationCookie(string username, string password) 
     { 
      string uriString = ServerName + AUTH_SERVICE_URL; 
      Uri uri = new Uri(uriString); 

      // Need to cast this to HttpWebRequest to set CookieContainer property 
      // With a null CookieContainer property on the request, we'd get an 
      // empty HttpWebRequest.Cookies property 
      HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; 
      request.Method = "POST"; 
      request.ContentType = "application/json; charset=utf-8"; 
      request.CookieContainer = new CookieContainer(); // needed to get non-empty Cookies collection back in response object 

      // requestContents needs to look like this: 
      // { 
      //  username = 'theUserName', 
      //  password = 'thePassword', 
      //  createPersistentCookie = false 
      // } 
      string requestContents = GetJsonForLoginRequest(username, password); 

      byte[] postData = Encoding.UTF8.GetBytes(requestContents); 
      request.ContentLength = postData.Length; 
      using (Stream dataStream = request.GetRequestStream()) 
      { 
       dataStream.Write(postData, 0, postData.Length); 
      } 

      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      if (response.StatusCode != HttpStatusCode.OK) 
      { 
       throw new WebException("Response returned HttpStatusCode " + response.StatusCode); 
      } 

      // For now, assuming response ContentType is "application/json; charset=utf-8" 
      object responseJson; 
      using (Stream responseStream = response.GetResponseStream()) 
      { 
       StreamReader reader = new StreamReader(responseStream); 
       string responseString = reader.ReadToEnd(); 

       responseJson = JavaScriptConvert.DeserializeJson(responseString); 
      } 

      if (responseJson is bool) 
      { 
       bool authenticated = (bool)responseJson; 
       if (authenticated) 
       { 
        // response was "true"; return the cookie 
        return response.Cookies[".ASPXFORMSAUTH"]; 
       } 
       else 
       { 
        // apparently the login failed 
        return null; 
       } 
      } 
      else 
      { 
       return null; 
      } 
     } 

接下來,將cookie添加到隨後的請求中。就我而言,這意味着將Cookie添加到我使用的Web服務代理的CookieContainer中。

+0

您是否使用Authentication_JSON_AppService.axd作爲AUTH_SERVICE_URL? 404例外有什麼問題嗎? – 2012-02-17 16:56:10

+0

我使用Authentication_JSON_AppService.axd/Login作爲AUTH_SERVICE_URL。 – 2012-02-20 18:10:33

+0

感謝您的回覆。是的,我試過了。無論出於何種原因,我無法使Authentication_JSON_AppService.axd/Login正常工作。編寫自定義身份驗證WebMethod非常簡單。 – 2012-02-20 19:09:22

0

我無法獲得authenticationService的工作。當我嘗試從我的winforms應用程序調用Authentication_JSON_AppService.axd時,我不斷收到404錯誤。所以我最終編寫了自己的JSON身份驗證WebMethod。

對不起,這不是C#,我的項目是VB.NET。我用這個http://progtutorials.tripod.com/Authen.htm作爲參考。

<WebMethod(EnableSession:=True)> 
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> 
Public Function Login(ByVal username As String, ByVal password As String) As Boolean 

    Dim result As Boolean = False 

    ' If (FormsAuthentication.Authenticate(username,password)) ' this may also work to authenticate 
    If (Membership.ValidateUser(username, password)) Then 
     FormsAuthentication.SetAuthCookie(username, False) 

     Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(username, False, 30) 
     Dim ticketString As String = FormsAuthentication.Encrypt(ticket) 

     Dim cookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, ticketString) 
     Context.Response.Cookies.Add(cookie) 

     result = True 

    End If 

    Return result 

End Function 

一定要讓您的web服務中的匿名用戶可以訪問您的身份驗證WebService。

<location path="Authentication.asmx"> 
    <system.web> 
     <authorization> 
     <allow users="*" /> 
     </authorization> 
    </system.web> 
    </location> 
相關問題