FormsAuthentication ASPXAUTH Cookie WCF and JSON



我有一个WCF Web服务,它公开函数以获取X信息。该服务以 JSON 格式返回信息。如果我想保护此 Web 服务,我需要做什么?不使用默认的 IIS 安全性,我想使用自定义登录(带数据库验证)。

我想从中显示 X 信息的客户端应用程序进行 JQUERY 和 AJAX 调用。首先,我有一个登录页面,我可以在其中输入用户名和密码(在MD5中加密)。客户端使用这些信息调用服务,如果用户有效(在 postgresql 数据库上简单选择)或 false,则服务返回 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

此致敬意

根据您的描述,我假设您正在使用 IIS 中的 http 绑定运行 WCF 服务。

如果在 web.config 中启用表单身份验证,ASP.NET 引擎将负责读取身份验证 cookie 并设置处理请求的线程的标识。您不必直接处理cookie。若要检查用户是否已通过身份验证,请检查 HttpContext.Current.User.Identity.IsAuthenticated 属性。

最新更新