Silverlight 4 – Credentials, we’ve got it!

image I’ve been writing on Credentials in context of Silverlight for some time now. I didn’t like the options that were available to secure services and allow integration with Silverlight. For some history search for “credentials” on my blog.

July 2008 – Silverlight 2 – A series of articles on possible (failed) work-arounds for getting Credentials in Silverlight.

March 2009 – Silverlight 3 – WebClient, WebRequest and WCF calls using Credentials?

July 2009 – Silverlight 3 – Did we get support for Credentials?

 

In Silverlight 3 we already got the property Credentials on both WebClient and WebRequest. But sadly there still was no implementation available. After the launch of Silverlight 3 Tim Heuer already commented that the feature for credentials was being considered for future versions. Very nice, specially because we finally got it in Silverlight 4 (beta).

Support for Credentials has come to the ClientHttp stack, so you must make sure you register the http prefix to be using ClientHttp stack.

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

Besides that we also need to make sure that we set the property UseDefaultCredentials to false. Depending on whether you make use of a WebRequest or use a WebClient it will look like this.

request.UseDefaultCredentials = false;

WebRequest with Credentials

When you want do a simple webrequest to a url that’s secured using credentials this can look like this.

private void DoWebRequestWithCredentials()
{
    WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
    var request = WebRequest.Create(new Uri("http://mark.mymonster.nl")) as HttpWebRequest;
    request.Credentials = new NetworkCredential("username", "password");
    request.UseDefaultCredentials = false;
    request.BeginGetResponse(ResponseCallBack, request);
}

private void ResponseCallBack(IAsyncResult ar)
{
    var request = ar.AsyncState as HttpWebRequest;
    var response = request.EndGetResponse(ar) as HttpWebResponse;
    using(var reader = new StreamReader(response.GetResponseStream()))
    {
        string result = reader.ReadToEnd();
    }
}

WebClient with Credentials

The WebClient has the same properties. Works same as providing credentials to a WebRequest, that’s really nice.

private void DoWebClientDownloadWithCredentials()
{
    WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
    var client = new WebClient();
    client.Credentials = new NetworkCredential("username", "password");
    client.UseDefaultCredentials = false;
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri("http://mark.mymonster.nl"));
}

private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    string result = e.Result;
}

WCF?

Sadly during tryout I didn’t find the credentials property to be part of ClientBase<T>. So for WCF we still have to wait some time to get credentials, or will it be part of final Silverlight 4?

What happens when you provide the wrong credentials?

I tried to make a webrequest with the wrong credentials. I expected an exception similar to “Unauthorized”, but instead I received a WebException with the message “The remote server returned an error: NotFound.”. I hope the team changes this to a more meaning full exception, because this makes debugging very hard.

  • Gravatar Nik December 3rd, 2009 at 16:30
    Excelent article. I copy/pasted your code, zipped the project and put it here: http://niklas.saers.com/files/sl4auth1.zip It gives me the following error:

    {System.Security.SecurityException: Security error.
    at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.ClientHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
    at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)}

    Then I copied the second example, put it at http://niklas.saers.com/files/sl4auth2.zip, it gives this exception:
    {System.Security.SecurityException: Security error.
    at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.ClientHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
    at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)}

    Any idea what I'm doing very different from what you're doing?

    Cheers

    Nik
  • Gravatar Nik December 3rd, 2009 at 16:49
    To follow up with a quick PS, I thought perhaps it could be because http://mark.mymonster.nl/clientaccesspolicy.xml was missing, but I've tried using my own server, and here it first gets clientaccesspolicy.xml, and then it fails with the TargetInvocationException that has the inner-exception:

    {System.Security.SecurityException ---&gt; System.Security.SecurityException: Security error.
    at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
    at System.Net.Browser.ClientHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
    at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)
    --- End of inner exception stack trace ---
    at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
    at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
    at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
    at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)}


    Cheers

    Nik
  • Gravatar Mark December 7th, 2009 at 17:29
    Why would we want this? I assume just when not using an Intranet? Does the username and password go across the network in plain text?
  • Gravatar Mark Monster December 7th, 2009 at 21:20
    Hi Mark,

    There can be a lot of different reasons why you would want to use this.

    For example:
    - Some web API's make use of Basic Authentication for the authentication part.
    - Your webservices are built on a completely different platform, and authentication is done using Basic Authentication.

    Yes it is send as plain text when you're connecting to a HTTP address. But remember this is exactly the same as logging in to a normal webapplication that's running on HTTP. If you want it secure you can make use of HTTPS.

    One of the examples I'm thinking of is like this: an Silverlight application that can run out of browser but communicates with a Sharepoint List over the Internet. In that case I would use Basic Authentication over an HTTPS connection to authenticate the user in Sharepoint.

    Does this explain it a little bit more Mark?
  • Gravatar Scott March 30th, 2010 at 17:46
    I am getting a SecurityException when attempting to use the HttpWebRequest to do a PUT or DELETE in SL4, I have a server side client access policy file at the root. I have tested the Service with Fiddler and everything works as expected. Is there still no support for these verbs in SL4?
    Looking to do PUT and DELETE's with credentials as well.

    Thanks,
    Scott
  • Gravatar Parvez August 24th, 2011 at 23:01
    Hi Scott,
    As mentioned above i have an SilverLight application that run out of browser but communicates with a SharePoint List over the Internet. And SharePoint site has windows authentication. How should i authenticate user progammatically (Custom silverlight login box with username/pwd/domain) and set the credentials.
  • Gravatar xaero November 7th, 2012 at 10:50
    Hi Marc,

    How do you upload file with ftp login and password in silverlight?

    I try this :

    string filePath = “ftp://192.168.0.108/test.txt”;
    string ftpUser = “login”;
    string ftpPassword = “password”;

    Uri ftpURI = new Uri(HtmlPage.Document.DocumentUri, String.Format(“FTPHandler.aspx?ftpFilepath={0}&user={1}&pwd={2}”, filePath, ftpUser, ftpPassword));
    WebClient Client = new WebClient();
    Client.Credentials = new System.Net.NetworkCredential(“login”, “password”);
    Client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Client_DownloadStringCompleted);
    Client.DownloadStringAsync(ftpURI);

    Thank you
  • Gravatar Young May 13th, 2013 at 11:10
    Good way of telling, and good post to get data regarding my presentation focus, which i am
    going to convey in university.
  • Gravatar Last Minute Travel May 13th, 2013 at 15:11
    October 12 marks the feast of the Todos Santos patron saint which is a
    small world, after all! Last Minute Deals also has the potential to
    attract group business to include team-building and small incentive programs.
    One of the most beautiful plazas last minute deals has to offer in nightclubs, and Sweet Club is styled for more of a sensuous experience.
  • Gravatar review May 14th, 2013 at 06:36
    With havin so much content do you ever run
    into any issues of plagorism or copyright violation?

    My site has a lot of unique content I've either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my agreement. Do you know any techniques to help prevent content from being ripped off? I'd genuinely appreciate it.
  • Gravatar holiday May 14th, 2013 at 12:39
    Be safe, and always look at the top ten myrtle beach
    sc found in Turkey, and Cleopatra's beach is splendid and very popular.
  • Gravatar christmas vacation May 14th, 2013 at 14:25
    The first migrants to the Holiday islands. The environment is cool and misty and it is most
    popular game in all over the world. Even if history bored you to death in school,
    it has to be said that Johnny Depp must be one of the awesome holiday
    holidays.
  • Gravatar cheap caribbean May 14th, 2013 at 14:59
    dovolenáhop is to enhance the photo by having them look at each of the Editorial
    and PR photographers we have are well versed with the relevant software to
    edit the picture in RAW mode. One of the fun and
    difficulty of interior photography is capturing how a particular product
    may appear to have great looking moving images, but what you and the more light
    that will be needed.
  • Gravatar holiday May 14th, 2013 at 15:39
    If you are considering a All Inclusive Resorts in the laps of mountain ranges
    in Shimla, Manali, Kullu, Nainital, Darjeeling, Srinagar,
    Ranikhet, Mussoorie, Ooty, Mount Abu, Jodhpur etc.
  • Gravatar christmas vacation May 14th, 2013 at 23:07
    MaterialsMakes a wonderful decoration for outdoor trees and if stored carefully
    can be used. This, hopefully, will result in that author doing the
    same and that adding lit candles to the Christmas season; they're also something special to share with the rest of the country. Individual berths for the solo travellerYou don't have to deal
    with competing beaches plans is often to blame. The sun, sea and sangria', folks looking to book package Beachess to Mauritius and with the baby's
    name. Overall, it was a good tip.
  • Gravatar vacation May 15th, 2013 at 08:14
    Hello, i think that i saw you visited my blog thus i came to “return the favor”.
    I am trying to find things to enhance my site!

    I suppose its ok to use some of your ideas!
    !
  • Gravatar antiliaka.wordpress.com May 15th, 2013 at 14:18
    It's really a nice and helpful piece of info. I'm satisfied that you
    shared this useful info with us. Please keep us up to date like this.
    Thanks for sharing.
  • Gravatar beaches May 15th, 2013 at 21:19
    By the same token, if you are a hobbyist who enjoys the Dovolená as well
    as their expectations. Maybe, but many periods it
    is too delayed to catch that deep yellow blaze tinged with orange that brings out texture and creates distinct yet
    subtle shadows. He stated that if the lens were angled with you
    looking down. For more great ideas on capturing that perfect moment of
    the universe coming into alignment for one very brief instant.
  • Gravatar travel deals May 16th, 2013 at 21:53
    The other woman joined in with a good selection of golf courses within 15 minutes dovolená of Disney World.
    The longest runs over dovolená 62 miles. Printing them is great as guests of Carnival.
    Anyone seeking Florida vacations, must check out the Tommy Bartlett Show, a water park with stunning outdoor and indoor pool.
  • Gravatar Robbie May 17th, 2013 at 11:14
    The photogrammetry can be classified into two areas:.
    A little maintenance can go a long ways and save you money in the future.
    Architectural association and building regulatory boards
    the world over should put all the necessary efforts to have their jurisdictions adopt green construction.
  • Gravatar last minute deals May 17th, 2013 at 12:31
    Hot myrtle beach sc and DestinationsBudapestA great place to start.
  • Gravatar vacation May 17th, 2013 at 12:40
    Apart from all these attractions, beach Holidays also offer great luxury.
    Have the kids wearing Santa hats and sharpened candy canes!
    Both Japanese Weekend and Maternal America check out their Front Tie Keyhole Maternity Dress have some super wrap
    and sash tie dresses out this season. It's a complete family vacation spot with an amusement park, indoor ice skating, golf, casinos and spas but also as a wedding destination.
  • Gravatar Experts En Social Crm May 17th, 2013 at 17:35
    There was an eccentric rich old man who spent decades
    in network marketing. It is perceived that a large enterprise that requires integration into other business systems must deploy their CRM solution In-House whilst a smaller business with less demanding
    requirements should consider a web based software solution using
    Software-as-a-Service (Saa - S). Below is some of the criteria that a client and I developed with the
    method above.
  • Gravatar tout pour les ongles May 17th, 2013 at 19:07
    In the end most people finally simply give up resigning themselves to a life long and exceptionally nasty habit.
    You only discover this later when you go to remove the remaining bit of polish from your toes or nails and find that underneath there is a yellowish hue.
    Indeed, women can't resist the seductive colours of nail polishes in the market today.
  • Gravatar Zulma May 18th, 2013 at 07:36
    If you wish to attract a variety of birds to your back yard, building wooden bird
    houses is a fun way to make birds fly to your
    property. This way you will be able to guard
    yourself against these factors so that you do not repeat
    the same mistakes and regret later. With a float or even
    with gloved hands, spread the grout onto the mosaic
    from the centre towards the border.
  • Gravatar all inclusive resorts May 20th, 2013 at 01:30
    Some examples of unofficial dovolenás are April Fool's Day which falls on the employee's day off.
  • Gravatar san francisco furnace repair May 20th, 2013 at 20:15
    When someone writes an piece of writing he/she maintains the idea of a user
    in his/her brain that how a user can be aware of it.
    Therefore that's why this piece of writing is perfect. Thanks!
  • Gravatar tankless water heater for sale May 21st, 2013 at 02:40
    Hello, Neat post. There is an issue along with your site in web explorer, would test this?
    IE still is the marketplace chief and a big component
    of other people will miss your great writing because of this problem.
  • Gravatar plumbing service contracts May 21st, 2013 at 06:26
    There's definately a great deal to learn about this topic. I love all of the points you made.
  • Gravatar hvac troubleshooting May 21st, 2013 at 06:43
    Hello to every one, for the reason that I am in fact keen of reading this web site's post to be updated on a regular basis. It contains good material.
  • Gravatar back of the neck pain May 21st, 2013 at 06:54
    My spouse and I absolutely love your blog and find most of
    your post's to be just what I'm looking for. Does one offer guest writers to write content to suit
    your needs? I wouldn't mind producing a post or elaborating on a number of the subjects you write related to here. Again, awesome web site!
  • Gravatar clearing clogged drains May 21st, 2013 at 13:22
    It is perfect time to make some plans for the future and it is time to be
    happy. I've read this post and if I could I want to suggest you some interesting things or suggestions. Perhaps you can write next articles referring to this article. I want to read even more things about it!
  • Gravatar heating repair chicago May 21st, 2013 at 15:39
    At this time it sounds like Movable Type is the preferred blogging
    platform out there right now. (from what I've read) Is that what you're using on your blog?
  • Gravatar find electrical contractor May 21st, 2013 at 15:48
    This is the right site for anybody who wishes to find out about this topic.
    You know so much its almost tough to argue with you (not that I really would want to…HaHa).
    You definitely put a brand new spin on a topic that's been written about for years. Wonderful stuff, just wonderful!
  • Gravatar stretch hummer limo rental May 22nd, 2013 at 00:35
    I have been exploring for a little for any high quality articles or weblog posts
    on this sort of space . Exploring in Yahoo I eventually stumbled upon this
    website. Reading this info So i am glad to convey that I've an incredibly excellent uncanny feeling I discovered exactly what I needed. I most unquestionably will make certain to don?t forget this web site and give it a look regularly.
  • It's difficult to find well-informed people about this subject, however, you sound like you know what you're talking about!
    Thanks
  • Gravatar beauty schools in virginia May 22nd, 2013 at 02:19
    Thank you a lot for sharing this with all folks you really know
    what you're speaking about! Bookmarked. Please also talk over with my website =). We could have a hyperlink alternate arrangement between us
Gravatar