HttpClient Adding JSON Authorization Header

三世轮回 提交于 2019-12-11 18:08:37

问题


I am running into an issue with authentication for the LogMeIn api. The authorization value is a JSON object. When running my code, I run into FormatException error.

"A first chance exception of type 'System.FormatException' occurred in System.Net.Http.dll Additional information: The format of value '{"companyId":9999999,"psk":"o2ujoifjau3ijawfoij3lkas3l2"}' is invalid."

        var client = new HttpClient();
        client.BaseAddress = new Uri("http://secure.logmein.com/public-api/v1/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Add("Accept", "application/JSON; charset=utf-8");

        string s = "{\"companyId\":9999999,\"psk\":\"o2ujoifjau3ijawfoij3lkas3l2\"}";

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(s);

       HttpResponseMessage response = client.GetAsync("authentication").Result;

How should I be formatting the authorization key in this situation?


回答1:


This happens, because LogMeIn does not use standard authentication schema like "Basic". You should add message header without validation:

string s = "{\"companyId\":9999999,\"psk\":\"o2ujoifjau3ijawfoij3lkas3l2\"}";
string h = "Authorization";

client.DefaultRequestHeaders.TryAddWithoutValidation(h, s);

See here and here

You can check that request you send have correct header using tool (web debugger) called Fiddler (It's a must have tool for web developer). You need to add the following configuration into web.config in order to route http traffic through Fiddler proxy:

<system.net>
   <defaultProxy>
       <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
   </defaultProxy>
</system.net>

or specify it in a request intself:

client.Proxy = new Uri("http://localhost:8888/"); // default address of fiddler



回答2:


I used RestSharp and was able to get it to authenticate.

        var request = new RestRequest(Method.GET);
        request.AddHeader("authorization", "{\"companyId\":9999999,\"psk\":\"o2ujoifjau3ijawfoij3lkas3l2\"}");
        request.AddHeader("accept", "application/Json; charset=utf-8c");
        IRestResponse response = client.Execute(request);

However, it still bugs me that I wasn't able to get it to work with the HttpClient.



来源:https://stackoverflow.com/questions/32898804/httpclient-adding-json-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!