3

Im using a web API to recieve an OAuth token which i want to process in my desktop application. The web API redirects the user to localhost:15779 on which i have my application listening using below class.
The problem here is that the API mentioned sends the token via HTTP GET but not using the query parameter (?key=value) but the fragment parameter (#key=value) and i cant change that behaviour because its not my API.
example:

http://127.0.0.1:15779/#access_token=b5c283xxxxxxxxe3lili5s003f5fqp&scope=chat_login+user_read

If you see the code below you will notice im writing the HttpListenerContext.Request.Url.Fragment into the recievedData variable in order to display it in the browser, for debug porposes. The thing is: its empty.

Any idea on how to get the token?

class HttpLstn
{
    public String prefixes;
    public static String recievedData = "";

    private static ManualResetEvent _waitHandle = new ManualResetEvent(false);

    public void start(string prefixes)
    {
        this.prefixes = prefixes;
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("Wrong listener URL");

        using (HttpListener listenOn = new HttpListener())
        {
            if (!listenOn.Prefixes.Contains(this.prefixes))
                listenOn.Prefixes.Add(this.prefixes);

            listenOn.Start();
            Thread.Sleep(100);
            IAsyncResult result = listenOn.BeginGetContext(new AsyncCallback(ListenerCallback), listenOn);
            _waitHandle.WaitOne();

            Thread.Sleep(100);
            listenOn.Close();
        }
    }

    public static void ListenerCallback(IAsyncResult result)
    {
        try
        { 
            HttpListener listenOn = (HttpListener)result.AsyncState;
            HttpListenerContext context = listenOn.EndGetContext(result);
            HttpListenerRequest request = context.Request;

            //DEBUG
            //write URL Fragment to recievedData in order to display it in the browser for testing purposes
            recievedData = context.Request.Url.Fragment;
            //DEBUG

            HttpListenerResponse response = context.Response;
            string responseString = recievedData;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();

            _waitHandle.Set();
        }
        catch (HttpListenerException he) { }
        catch (ObjectDisposedException oe) { }
    }
}
LemoniscooL
  • 95
  • 1
  • 6

1 Answers1

2

I just ran into this too. Turns out browsers don't send the fragment portion to the server; they keep it and use it to scroll to the indicated portion of the returned document.

https://stackoverflow.com/a/14462350/723299

Community
  • 1
  • 1
John Hatton
  • 1,734
  • 18
  • 20