FormsAuthentication ASPXAUTH Cookie WCF和JSON

问题描述:

我有一个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 

最好的问候,

从你的描述,我假设你使用的是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