×

First time here?

You are looking at the most recent posts. You may also want to check out older archives. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS or email. Thank you for visiting!

A little bit of hidden gem in the Silverlight 4 release is the ability to modify the Authorization header in network calls.  For most, the sheer ability to leverage network credentials in the networking stack will be enough.  But there are times when you may be working with an API that requires something other than basic authentication, but uses the Authorization HTTP header.

The Details

Basically you just set the header value.  How’s that for details :-). 

Seriously though, here’s a snippet of code:

   1: WebClient c = new WebClient();
   2: c.Headers[HttpRequestHeader.Authorization] = "Auth header from same domain-browser stack";
   3: c.DownloadStringCompleted += ((s, args) =>
   4:     {
   5:         if (args.Error != null)
   6:         {
   7:             response.Text = args.Error.Message;
   8:         }
   9:         response.Text = args.Result;
  10:     });
  11: c.DownloadStringAsync(new Uri(http://localhost:4469/handler.ashx));

As you can see in the code is rather simple.  Prior to Silverlight 4 you’d receive an exception that setting the header isn’t possible…but now it is.  If you are using HttpWebRequest instead it would be just as simple:

   1: HttpWebRequest req = (HttpWebRequest)WebRequest.CreateHttp("http://localhost:4469/handler.ashx");
   2: req.Headers[HttpRequestHeader.Authorization] = "Auth header from same domain using HWR";
   3: req.BeginGetResponse((cb) =>
   4:     {
   5:         HttpWebRequest rq = cb.AsyncState as HttpWebRequest;
   6:         HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse;
   7:  
   8:         StreamReader rdr = new StreamReader(resp.GetResponseStream());
   9:         string foo = rdr.ReadToEnd();
  10:         Dispatcher.BeginInvoke(() =>
  11:             {
  12:                 response.Text = foo;
  13:             });
  14:         rdr.Close();
  15:  
  16:     }, req);

That’s it.

The Support Matrix

As such this feature does have some restrictions for security reasons.  Basically the difference has to do with cross-domain calls.  Here’s the feature support matrix in the simplest terms:

Network Stack Used Domain Type Authorization Header Allowed
Browser (default) same domain Yes
ClientHttp same domain Yes
Browser (default) cross-domain Yes with policy
ClientHttp cross-domain Yes with policy

As you can see a cross-domain call of this (i.e., setting an Authorization header on a 3rd party site) would require that a valid clientaccesspolicy.xml be in place.  Here’s an example of a pretty liberal one:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <access-policy>
   3:     <cross-domain-access>
   4:         <policy>
   5:             <allow-from http-request-headers="Content-Type,Authorization">
   6:                 <domain uri="*"/>
   7:             </allow-from>
   8:             <grant-to>
   9:                 <resource include-subpaths="true" path="/"/>
  10:             </grant-to>
  11:         </policy>
  12:     </cross-domain-access>
  13: </access-policy>

I should note that when I mean ‘pretty liberal’ this means that the above makes all your resources available to all Silverlight clients.  But pay attention to the http-request-headers section.  Notice the addition of the Authorization header (Content-Type is default always).  By adding this you would be able to have a cross-domain Authorization header writing ability.  Without it you’d see a security exception.  And remember, the policy files exist on the destination endpoint and not in your app.  To demonstrate this, here’s my quick sample application output:

Auth header sample app output

You can download the code for this sample tester application here: Authheaders.zip

Summary

Hopefully this is good news to some developers.  Now with Silverlight 4 we have network credentials support and the ability to use the Authorization header when needed for other purposes.  It’s a little hidden gem that frankly could have been better called out in the docs a bit.

Hope this helps!

This work is licensed under a Creative Commons Attribution By license.


4/25/2010 2:12 AM | # re: Silverlight 4 enables Authorization header modification
Thnx for the post.

There is a small error in your first snippet: when an error is found in line 5, it will be assigned to response.Text in line 7, but it will be overwritten in line 9.
4/26/2010 6:43 AM | # re: Silverlight 4 enables Authorization header modification
Hi Tim,
I'm wondering is it possible to access a webservice with Windows Auth?
Is it possible to just set the header NTLM, if I do this will it authenticate to the webservice?
Thanks
6/4/2010 10:47 AM | # re: Silverlight 4 enables Authorization header modification
Hi Tim,

I was wondering about a specific scenario. I have a HTTPS Java Web Service which is wsdl compliant and is being referenced from Silverlight. The thing is that if I call a method on the web service I'm prompted in Internet Explorer to enter the credentials for the web service. This happens only for the first web service call.
How can I avoid this credential prompt? I want to be able to specify the credentials in code.

Thanks
6/4/2010 10:57 AM | # re: Silverlight 4 enables Authorization header modification
Florin, using the client networking stack you can provide a NetworkCredential to the service call.
6/16/2010 2:30 AM | # re: Silverlight 4 enables Authorization header modification
Anyone who is bashing their heads getting similar code working for authentication in sl4 notice tim has this line:

WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

Which ensures that the request is using the new network stack that supports settings authorization headers. Took me 30 mins to notice the difference between tims code and mine!
6/30/2010 8:58 PM | # re: Silverlight 4 enables Authorization header modification
I have a soap webservice on SSL, with basic authentication. I have a silverlight 4 client app that needs to connect to this service. The problem I have is that the credentials supplied in code are ignored (even though I specify the clienthttp stack) - and a popup prompts for the login. How can I avoid this annoying popup prompt. I don't know how to make credentials be honored by the "service reference" proxy class.
8/13/2010 9:26 AM | # re: Silverlight 4 enables Authorization header modification
Has anyone else had trouble with adding the Authorization header? I've used this:
HttpWebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);

SL4.0, and after inspecting the Fiddler2 Auth & headers, i can see it's not being added to the request, even though I've the code to do so:

wc.Headers[HttpRequestHeader.Authorization] = "Basic " + EncodeTo64(":admin");

Tim, what do you make of this?

thanks much,
Greg
11/3/2010 9:33 PM | # re: Silverlight 4 enables Authorization header modification
Thx Tim, you have written great article again. ^^
3/7/2011 11:47 PM | # re: Silverlight 4 enables Authorization header modification
Hi Tim,
I have a soap web-service, with basic authentication. I have a silverlight 4 client app that needs to connect to this service. The problem I have is that the credentials supplied in code are ignored (even though I specify the clienthttp stack) - and a pop-up prompts for the log-in. How can I avoid this annoying popup prompt. I don't know how to make credentials be honored by the "service reference" proxy class.

Please help me...

Regards,
Raghu
3/12/2011 6:06 AM | # re: Silverlight 4 enables Authorization header modification
I have a soap webservice on SSL, with basic authentiMB2-632 test cation. I have a silverlight 4 client app that needs to connect to this service. The problem I have is that the credentials supplied in code are ignored 70-433 test (even though I specify the clienthttp stack) - and a popup prompts for the login. How can I avoid this annoying popup prompt. 70-270 test I don't know how to make credentials be honored by 70-686 test the "service reference" proxy class.




Gravatar
3/30/2011 1:55 PM | # re: Silverlight 4 enables Authorization header modification
This is absolutely what I am looking for. This would help me with my research... Arredi industriali
4/4/2011 4:30 PM | # re: Silverlight 4 enables Authorization header modification
thanks, i will hope it helps me in the future. dont forget to visit Sexanzeigen too, thx
4/9/2011 12:45 AM | # re: Silverlight 4 enables Authorization header modification

The ascending is story in garment a breaking ordinal and it entails idiosyncratic perdurable render for me. I am determining to wee your towering way of connector the playacting. Now you fitness it macerate for me to micturate and get the involvement. Add you for the airman.

love life quotes
4/11/2011 8:02 AM | # re: Silverlight 4 enables Authorization header modification
Is there any way to allow silverlight to handle the credentials challenge from a server which requires basic authentication? As it stands the browser intercepts the 401 not authorized and puts up the userid/password dialog. I want to handle that programmatically in my silverlight client. any way to do that???
Gravatar
5/16/2011 2:39 AM | # re: Silverlight 4 enables Authorization header modification
In May 1817 General Convention, the governing body of the Episcopal Church, met in New York City and passed two resolutions. One was to found a General Episcopal Seminary to be supported by the whole church, and the second that it be located in New York City. Founders included John Henry Hobart, Theodore Dehon, and William White Oilseed Flaking
Gravatar
6/13/2011 3:20 AM | # re: Silverlight 4 enables Authorization header modification
I got some very unique information which are really very helpful for anyone. This is a post owning some crucial information. I wish that in future such posting should go on. Wheat Flour Milling Machinery
7/6/2011 12:10 AM | # re: Silverlight 4 enables Authorization header modification
No doubt The information presented is quite useful. By using this ceh I think all can prevent major breakdown mcsa
7/8/2011 7:13 AM | # re: Silverlight 4 enables Authorization header modification
@ Kris, you should try with UseDefaultCredentials set to false. I think it's gonna be ok then.
Georges from ustensiles de cuisine
7/13/2011 9:26 AM | # re: Silverlight 4 enables Authorization header modification
I have with soap web service is SSL, basic authentication. I have four Silverlight client app that is a access this service.
Places to visit in new york
7/16/2011 6:30 AM | # re: Silverlight 4 enables Authorization header modification
I am certainly thankful to you for providing us with this invaluable info.
Body Mist
Gravatar
9/9/2011 4:02 AM | # re: Silverlight 4 enables Authorization header modification
A little bit of hidden gem in the Silverlight 4 release is the ability to modify the Authorization header in network calls. For most, the sheer ability to leverage network credentials in the networking stack will be enough.
barbering school
9/19/2011 10:41 AM | # re: Silverlight 4 enables Authorization header modification
It's great having the authorization to modify the header. Now my site is more customizable and dynamic.
how to get amex black card
9/23/2011 2:55 AM | # re: Silverlight 4 enables Authorization header modification
Many people will obviously agree that your post was really interesting and that I can’t wait around to acquire more information. travel
11/20/2011 11:33 PM | # re: Silverlight 4 enables Authorization header modification
Hey Tim,

Is it possible to set "Accept-Encoding" header thru HttpWebClient? By default it sets value "identify" but I wanted it to have "gzip, deflate".

Is there a way to do it?
4/26/2012 7:22 AM | # re: Silverlight 4 enables Authorization header modification
I have to say thanks. Your post will really help me for one of the issue in my job. Thanks again.

 
Please add 8 and 4 and type the answer here:

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.