Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a custom string in "Authorization" header in System.Net.HttpClient

I am trying to use the System.Net.HttpClient class to post a message to Google Cloud Messaging.

Google Cloud Message requires you to include a header called "Authorization", in a format similar to this:

key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D

But the HttpClient class throws an exception when I try this.

string keyString = "key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0LJ0w";
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Foo", keyString); // <== Proving I can
    client.DefaultRequestHeaders.Add("Authorization", keyString); // Exception thrown

The exception is of type System.FormatException. The message is

The format of value 'key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0LJ0w' is invalid.

And the callstack is:

at System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
at System.Net.Http.Headers.HttpHeaders.ParseAndAddValue(String name, HeaderStoreItemInfo info, String value)
at System.Net.Http.Headers.HttpHeaders.Add(String name, String value)

How can I get this header into this post request without an exception being thrown?


Incidentally, I have composed a post like this using Fiddler, and it works:

Headers:

User-Agent: Fiddler
Authorization: key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D
Host: android.googleapis.com
Content-Length: 220
Content-Type: application/json

Request Body:

{
 "registration_ids" : ["APA91bEM6XPdiZv5VgNNApakfyYfZwB871018Hljl1L27kaPvksasnR0bHlmcCZFxOSPD6bDLMZgvgfT9xsKnF6Tg0oSQM2cMM1KRbuK7cR7jICqAnSDYg_SvERTzPMT8puXGTlVkEVH6dsneBkXiBu6pZikWXWyRATAVbXnAHTe20-nQerb0"],
}
like image 508
Andrew Shepherd Avatar asked May 08 '14 07:05

Andrew Shepherd


2 Answers

Try this answer instead:

https://stackoverflow.com/a/24575721/1981387

Seems like a bit of a workaround, since it's a string pair instead of a nice object, but it seems to work.

like image 83
welegan Avatar answered Sep 20 '22 13:09

welegan


That's because your value is breaking the HTTP specification.

The header should contain Authorization: scheme SPACE value as described here: http://www.ietf.org/rfc/rfc2617.txt

In your case:

Authorization: key AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D
like image 41
jgauffin Avatar answered Sep 20 '22 13:09

jgauffin