2012-07-05 67 views
1

我有一個WCF Web服務,公開函數來獲取X信息。該服務以JSON格式返回信息。 如果我想要保護此Web服務,我需要做什麼?不使用默認的IIS安全性,我想使用自定義登錄(使用數據庫驗證)。FormsAuthentication ASPXAUTH Cookie WCF和JSON

我想從中顯示X信息的客戶端應用程序使JQUERY和AJAX調用。首先,我有一個登錄頁面,可以輸入用戶名和密碼(在MD5中加密)。客戶使用這些信息調用服務,如果用戶有效(簡單地在postgresql數據庫上選擇)或服務返回YES,服務返回YES。目前,我啓動一個FormsAuthentication對象並將其添加到cookie中。

Private Function SetAuthCookie(name As String, rememberMe As Boolean, userData As String) As Integer 

    ' In order to pickup the settings from config, we create a default cookie and use its values to create a new one. 
    Dim cookie As HttpCookie = FormsAuthentication.GetAuthCookie(name, rememberMe) 
    Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(cookie.Value) 

    Dim newTicket As New FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData, ticket.CookiePath) 
    Dim encTicket As String = FormsAuthentication.Encrypt(newTicket) 

    ' Use existing cookie. Could create new one but would have to copy settings over... 
    cookie.Value = encTicket 

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

    Return encTicket.Length 
End Function 

其次,我看到,當我從客戶端代碼做呼叫,.ASPXAUTH的cookie被傳遞每個調用。 但是,我需要在服務器端做什麼來驗證這是一個好用戶而不是一個「被盜」的cookie的ASPXAUTH代碼?我不認爲這個小的isValidUser函數足以有效地調用。

Private Function isValidUser() As Boolean 
    Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName) 

    If cookie Is Nothing Then Return False 

    Dim decrypted = FormsAuthentication.Decrypt(cookie.Value) 

    If String.IsNullOrEmpty(decrypted.UserData) Then Return False 

    Return True 
End Function 

最好的問候,

回答

1

從你的描述,我假設你使用的是HTTP IIS內運行結合WCF服務。

如果您在web.config中啓用表單身份驗證,則ASP.NET引擎將負責讀取身份驗證cookie並設置處理請求的線程標識。你不應該直接處理cookie。要檢查用戶是否已通過身份驗證,請檢查HttpContext.Current.User.Identity.IsAuthenticated屬性。

+0

Anders, 我使用IIS的webHttpBinding。當我查看用戶標識時,在本地主機上我有Windows認證用戶,但是當我將Web服務發佈到另一臺服務器時,該屬性爲空。無論如何,我不需要Windows Authenticated用戶,我需要使用存儲在postgres數據庫中的用戶名和密碼對我進行身份驗證。 感謝您的幫助。 – 2012-07-06 13:53:51