Can't get HTTP POST Basic Auth to work

I’ve been trying to get an access token from freeagent for a while and can not find any reason why this code doesn’t work.

Seems like HTTP basic auth just isn’t working.

One issue I have bypassed is an SSL issue as well.

App settings:

<add key="FreeAgentConsumerKey" value="1gohv0NDO9hNxKG6NopXuw" />
<add key="FreeAgentConsumerSecret" value="qwRQJypi8NiHu5pRrTWBbQ" />
<add key="FreeAgentBaseUrl" value="https://api.sandbox.freeagent.com/v2" />
<add key="FreeAgentTokenEndpoint" value="/token_endpoint" />
<add key="FreeAgentTokenApproveApp" value="/approve_app" />
<add key="FreeAgentOauthAuthCallbackUrl" value="/Admin/FreeAgent/GetAccessCodeFromAuthCode" />
<add key="FreeAgentOauthCallbackUrl" value="/Admin/FreeAgent/FreeAgentResponse" />

            string url = CompleatConfiguration.AppSettings["FreeAgentBaseUrl"] + CompleatConfiguration.AppSettings["FreeAgentTokenEndpoint"];
            string code = Request.QueryString["code"].ToString();
            string callbackURL = Request.Url.GetLeftPart(UriPartial.Authority) + CompleatConfiguration.AppSettings["FreeAgentOauthCallbackUrl"];
            string credentailString = CompleatConfiguration.AppSettings["FreeAgentConsumerKey"] + ":" + CompleatConfiguration.AppSettings["FreeAgentConsumerSecret"];
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentailString));
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentailString);
            client.DefaultRequestHeaders.Host = "api.freeagent.com";
            client.DefaultRequestHeaders.ConnectionClose = true;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Java", "1.6.0_33"));
            var values = new Dictionary<string, string>
            {
                { "grant_type", "authorization_code" },
                { "code", code },
                { "redirect_uri", UriUtility.UrlEncode(callbackURL) },
            };
            var content = new FormUrlEncodedContent(values);
            HttpResponseMessage response = await client.PostAsync(url, content);
            var t = response.Content.ReadAsStringAsync();

Hi, Richard.

Is it possible it’s because you’re using credentailString instead of the base64 encoded version of that string (credentials) in this line:

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentailString);

You may also want to make sure that client.DefaultRequestHeaders.Host is set correctly.

If you resolve that and are still having issues, I’d be interested in seeing the results you’re getting at each step in your code to verify that all looks right.