从非 Web 客户端调用 ASP.NET 2.0 身份验证服务

发布于 2024-09-14 09:36:26 字数 592 浏览 5 评论 0 原文

我正在开发一个调用 ASP.NET 2.0 网站的 .NET 2.0 winforms 应用程序。该网站使用表单身份验证进行身份验证。在 web.config 中启用了身份验证服务,并且我做了一些 实验以确认我可以通过 JSON 访问该服务。

我的问题是:是否有任何内置代码可以在纯.NET环境(不是ASP.NET)中使用System.Web.Extensions Web服务(authenticationService、profileService等)?我可以找到使用 Silverlight 和后来的 WCF 服务的示例,但在客户端和服务器上都找不到 2.0 环境中的任何内容。将身份验证服务添加为 Web 服务似乎是合乎逻辑的方法,但我永远无法让它指向我的开发服务器 - 我想这可能是一个单独的问题。

如果我必须在较低级别管理 AJAX 请求和响应,这当然是可行的,但如果某些东西已经用于此目的,那么它肯定会更容易并且更不容易出错。

I am working on a .NET 2.0 winforms application that calls an ASP.NET 2.0 website. The website is authenticated using forms authentication. The authentication service is enabled in the web.config, and I have done some experiments to confirm that I can access the service via JSON.

Here is my question: is there any built-in code to consume the System.Web.Extensions web services (authenticationService, profileService, etc.) in a purely .NET environment (not ASP.NET)? I can find examples using Silverlight and the later WCF services, but not anything in a 2.0 environment on both client and server. Adding the authentication service as a web service seems like the logical approach, but I could never get it to work pointing to my development server - I suppose that could be a separate question.

If I have to manage the AJAX request and response at a lower level, it's certainly doable, but if something were already intended for this purpose it would certainly be easier and less error-prone.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

琉璃梦幻 2024-09-21 09:36:26

我从来没有得到这个问题的答案,但最终在 本教程。简短的回答是肯定的,我必须在相当低的级别上管理 AJAX 请求/响应。假设您有需要进行身份验证的用户名和密码,您首先需要为其获取身份验证 cookie。我使用 Newtonsoft 的 Json.NET 库 进行 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 中。

I never got an answer for this, but eventually figured it out with the help of this tutorial. The short answer was yes, I had to manage the AJAX request/response at a fairly low level. Assuming you have a username and password you need to authenticate with, you first need to get an authentication cookie for it. I used the Json.NET library from Newtonsoft for the JSON serialization and deserialization, but you could use anything.

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;
            }
        }

Next, add the cookie to subsequent requests. In my case, that meant adding the cookie to the CookieContainer of the web service proxy I was using.

如梦初醒的夏天 2024-09-21 09:36:26

我无法让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.config 中的匿名用户可以访问您的身份验证 WebService。

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

I was not able to get the authenticationService working. I kept getting 404 errors when I tried to call Authentication_JSON_AppService.axd from my winforms application. So I ended up writing my own JSON authentication WebMethod.

Sorry it's not C#, my project is VB.NET. I used this http://progtutorials.tripod.com/Authen.htm as a reference.

<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

Be sure to make your authentication WebService accessible to anonymous users in your web.config.

  <location path="Authentication.asmx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文