4

I have searched "ASP.NET authentication from a Windows Forms application" on google, but the results are "Windows Authentication using ASP.NET" which is not what I am looking for.

Scenario:

I have an ASP.NET application and a set of WCF services what provide data to the application via AJAX calls. These WCF services require ASP.NET authentication, which is fine from the browser because there is a cookie which provides the authentication information, or asks the user to authenticate via a login page.

I need to call these services from a Windows Forms application, without changing the way they work. i.e. The Windows Forms application will receive the JSON data from the service and process it.

Problem:

I need to be authenticated before I can use the WCF services, but as this is not a web application, there is no cookie, and the login page cannot be displayed!

Question:

How do I provide authentication from a Windows Forms application to an ASP.NET web application?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313

1 Answers1

5

You need to store cookies for each request like browser. Once you send a request for log in form, cookie variables keep you authenticated for next requests.

static class Requester
{
    static CookieContainer cookieJar = new CookieContainer();
    static string userAgent = ""; //specify your user agent

    /// <summary>
    /// Static method to request a web page. 
    /// It acts like a browser which means that keeps all cookies for depending domain.
    /// </summary>
    /// <param name="URL"></param>
    /// <returns></returns>
    static public FinalResponse sendRequest(string URL)
    {
        return sendRequest(URL, "");
    }


    static public FinalResponse sendRequest(string URL, string parameters)
    {
        FinalResponse result = new FinalResponse();
        Stopwatch timer = new Stopwatch();
        HttpWebRequest request;

        try
        {
            request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Referer = "http://google.com"; //specify your referer
            request.CookieContainer = cookieJar;
            request.UserAgent = userAgent;
            BugFix_CookieDomain();
            request.AllowAutoRedirect = true;
            if (parameters != "")
            {
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = parameters.Length;

                //push parameters to request stream
                StreamWriter myWriter = new StreamWriter(request.GetRequestStream());
                myWriter.Write(parameters);
                myWriter.Close();
            }
            //send request
            result.requestTime = DateTime.Now;
            timer.Start();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            timer.Stop();
            result.responseMilliseconds = timer.ElapsedMilliseconds;
            BugFix_CookieDomain();
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                result.document = sr.ReadToEnd();
                sr.Close();
                result.isSucceded = true;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            result.document = "";
            result.isSucceded = false;
        }
        return result;
    }


    /// <summary>
    /// Call this function before all usage of cookieJar. 
    /// It fixes the bug (!) of CookieContainer Class. 
    /// </summary>
    private static void BugFix_CookieDomain()
    {
        System.Type _ContainerType = typeof(CookieContainer);
        Hashtable table = (Hashtable)_ContainerType.InvokeMember("m_domainTable",
                                   System.Reflection.BindingFlags.NonPublic |
                                   System.Reflection.BindingFlags.GetField |
                                   System.Reflection.BindingFlags.Instance,
                                   null,
                                   cookieJar,
                                   new object[] { });
        ArrayList keys = new ArrayList(table.Keys);
        foreach (string keyObj in keys)
        {
            string key = (keyObj as string);
            if (key[0] == '.')
            {
                string newKey = key.Remove(0, 1);
                table[newKey] = table[keyObj];
            }
        }
    }
Can Guney Aksakalli
  • 1,320
  • 1
  • 11
  • 24
  • Nice example. Only thing missing is a ref to the bug your code 'fixes' in the cookieContainer - just so we know what you are actually addressing and if the bug is still present. – beterthanlife Dec 15 '14 at 13:09
  • @beterthanlife Thank you. Here is where I got this workaround: http://stackoverflow.com/questions/1047669/cookiecontainer-bug – Can Guney Aksakalli Dec 19 '14 at 01:09