Calling ASP.NET 2.0 Authentication Service from Non-Web Client

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

Here is my question: is there any built-in code for using the System.Web.Extensions web services (authenticationService, profileService, etc.) in a clean .NET environment (and not ASP.NET)? I can find examples using Silverlight and later WCF services, but not anything in 2.0 on the client and server. Adding an authentication service as a web service seems like a logical approach, but I couldn’t get it working by pointing to my development server. I suppose this may be a separate issue.

If I need to manage the AJAX request and response at a lower level, this is certainly possible, but if something is already intended for this purpose, it will certainly be simpler and less error prone.

+3
source share
2 answers

I never received an answer to this question, but in the end I realized this with the help of this lesson . 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 with which you need to authenticate, you first need to get an authentication cookie for it. I used the Json.NET library from Newtonsoft to serialize and deserialize JSON, but you could use something.

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

Then add the cookie to subsequent requests. In my case, this meant adding a cookie to the CookieContainer of the web service proxy that I used.

+1
source

authenticationService . 404 , Authentication_JSON_AppService.axd winforms. , - JSON.

, #, - 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

WebService web.config.

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

Source: https://habr.com/ru/post/1759344/


All Articles