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 home care solutions May 28th, 2014 at 01:20
    Wow, that's what I was seeking for, what a stuff! present here at this webpage,
    thanks admin of this website.
  • Gravatar ray ban 3025 June 19th, 2014 at 03:49
    Ehemalige Bethlehem College-Student David Fellows hat sich in den Absturz, der drei Neuseel盲nder in Kenia, mit den Ermittlern sagte, er sei nicht der Fahrer get枚tet gel枚scht wurde.
  • Gravatar seo company July 2nd, 2014 at 09:46
    Fantastic beat ! I wish to apprentice while you amend your website, how could i
    subscribe for a blog site? The account helped me a acceptable
    deal. I had been a little bit acquainted of
    this your broadcast offered bright clear concept
  • If some one wants expert view on the topic of
    blogging and site-building then i propose him/her to go
    to see this web site, Keep up the good work.
  • Gravatar Super Discount Auto Glass July 26th, 2014 at 00:06
    Genuinely when someone doesn't know afterward its up to other users
    that they will assist, so here it takes place.
  • Gravatar and fitch August 7th, 2014 at 07:45
    Safety Brandon Meriweather is returning to the Washington Redskins.
  • Gravatar Trent August 15th, 2014 at 20:08
    I know this site offers quality dependent content and
    additional information, is there any other website which gives such information in quality?
  • Cheng Lin momma mother contains use returning Nagasawa set off. Don't be for that reason courteous goodness me! Normal water this little ones express, {nevertheless|although|nonetheless|however , k .
  • Gravatar activity tracker Watch Sleep August 31st, 2014 at 23:10
    I must thank you for the efforts you have put in penning this site.
    I'm hoping to see the same high-grade content from
    you in the future as well. In fact, your creative writing abilities has motivated me to get my very own blog now ;)
  • Gravatar Hye September 6th, 2014 at 20:40
    I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but certainly you're going to a famous
    blogger if you are not already ;) Cheers!
  • Gravatar belinnmt.buzznet.com September 7th, 2014 at 09:20
    Pretty! This was an extremely wonderful post. Many
    thanks for supplying this info.
  • Gravatar Ab Exercise Machines India September 9th, 2014 at 05:34
    I drop a leave a response whenever I like a article on a site or if I have something to add to the conversation. Usually it is caused by the fire communicated in the article I read.
    And on this post Silverlight 4 – Credentials, we’ve got it!

    - Silverlight, WP7, .NET, C#, ASP.NET MVC. I was actually excited enough to drop a thought :-) I actually do
    have 2 questions for you if you usually do not mind. Is it only me or do some of the responses
    come across like coming from brain dead folks?
    :-P And, if you are posting on additional online
    social sites, I would like to keep up with everything new
    you have to post. Could you list the complete urls
    of your community sites like your twitter feed, Facebook page or linkedin profile?
  • Gravatar yakima bike roof rack September 10th, 2014 at 15:29
    Thanks for ones marvelous posting! I actually enjoyed reading it, you can be a great author.

    I will always bookmark your blog and may come back sometime soon. I want to encourage yourself
    to continue your great writing, have a nice day!
  • Gravatar Cash Advance In Claymont Delaware September 14th, 2014 at 23:55
    The most affordable Software On-line cheap OEM software blog :
    invest in software package great buy price tag.
  • Gravatar louboutin femme talon noir September 21st, 2014 at 12:12
    However, Mrs Cooper and her dedicated staff are determined their school will end on a high and they are busy planning a programme of special events to celebrate its proud history and achievements.
  • Gravatar gucci premium outlet usa September 22nd, 2014 at 22:18
    You can use mnemonics to help you remember the spelling of tricky words, the names of people at a dinner party or your children's friends names. Rhyming mnemonics are especially good because the sound and structure helps keep the words in the right order.
  • Gravatar hogan scontate September 23rd, 2014 at 06:10
    Le groupe quitte le Monkey Bar avec les plans de la queue pour entrer dans le comble, en sueur Cadillac Ranch. La musique country joue fort de l'intérieur, et ce fournit la ligne à l'extérieur avec plus d'énergie. Comme tout le monde peut le voir, le Cadillac Ranch s'adresse à la foule de pays, qui semble être à peu près tout le monde dans Fargo. Mais il n'est pas difficile d'être le pays à Fargo. Tout ce qu'il faut est une appréciation de la musique pop avec un accent et les paroles des mineurs sur l'agriculture / élevage / combat / femmes / alcool / camionnettes / d'être un cow-boy ou cow-girl à part entière. Tout le monde est allé pays pourrait être la meilleure, la plus logique, orientée de façon empirique d'une déduction peut faire en faisant la queue pour entrer dans le Cadillac Ranch.
  • Gravatar louboutin femme fitness 15e September 24th, 2014 at 13:38
    The rest of Mrs. Obama's Inauguration Day outfit included a belt from J. Crew, necklace by Cathy Waterman and a cardigan by Reed Krakoff, whose ensemble she also wore to yesterday's intimate, indoor swearing in ceremony.
  • Gravatar Alix A. Rviz September 24th, 2014 at 17:02
    I do not even know the way I finished up here, however I assumed this post used to be good.
    I do not realize who you might be but certainly you are going to a well-known blogger if you aren't already.
    Cheers!
  • Gravatar buy cheap real jordans September 24th, 2014 at 22:42
    Buy the very cheap jordans free shipping all over the world,our retro jordan shoes all sizes for men and women, buy cheap real jordans
  • Gravatar payday loans uk bad credit September 25th, 2014 at 02:06
    The consumer is guaranteed via advertisement to receive any desired solution at a certain low price
    however if they go through the retailer, these people find no such piece at that affordable price; however, your retailer prospects them to the
    'similar' item that has a higher price Except in cases where your family member or
    buddy is a financial professional, the real key is not going to manage to offer you moral support you
    need With these loans, you can avail provide for that ranges from $100 to help $1500 for easy loan term
    of 2-4 weeks Those who didn't at all like me, just
    because associated with my girl or boy, people that couldn't like me since i didn't seem as cheerful as many of the
    other people This personal tool makes it possible for a consumer for you to consolidate in to
    one loan several as well as different student loan contracts If
    your student goes in for these financial products he can employ a lot
    of strain on them removed in terms of the financial matters come to mind and he can put in her time in his studies This means credit
    seekers who have frequently CCJS, arrear, have very delinquent on expenses or
    did not make obligations in the past get instant payday loans inside of
    a quick and easy manner There is a cap near $45,000 property value forgiveness for new
    financial loans, but if you might be repaying financial products incurred before the signing of the bill, there isn't
    a cap in the least Yet, the option of arranging the full quantity for exterior source can be
    not a possible decision regarding him Additional to that is certainly the fact
    that personalized financial loans are often for more significant
    quantities of income - in the event you only have to borrow a number of $ 100 to hold you over till
    the following payday, a certain personal loan is just not even appropriate to your features Your loan is
    going to be approved by the amount you obtain as type
    of pension every month Fast-tracking the successful city
    of Berlin into the spotlight, company discussed what it is fast becoming a natural hub to get budding business people striving to make their level on the a
    digital scene Instant Cash Financial products are small tenure advances that are fitted for remunerated people to get
    over their cash issues in the middle of of the calendar month Prior
    to you apply just for this scheme you will need to fulfil the examples below criteria which might be mentioned under: If you
    are bad credit holders, actually than it is possible to take
    make use of taking these financing options because lenders of cash financial products to your
    front door do not call for credit checking in the process of giving loan One of many multi-purpose loans is actually payday loan zero credit check where
    you could enjoy the benefits of a loan without having inviting any sort of credit
    checking out hassles As per instructions of the fund agencies, the particular borrowers upload the
    loan application online and that is free from quite a
    few formalities Men and women, in contrast, have to take more
    jobs compared to what they could possibly do and also save a great deal of money as they
    are able The credit given to a borrower is dependent upon its current
    earnings and its repaying ability Simply because this was your second of the sort around recent 2 or 3 weeks the issue connected
    with student loan credit debt, which not long ago surpassed
    your $1 trillion $ mark, elements into several young People in america worries The Scheduling details business makes up
    the supply of cigarettes and tobacco products for smoking
    cigarettes product producers, including Imperial
    Cigarettes, as well as a choice of non-tobacco products and services
  • Gravatar コーチ September 25th, 2014 at 06:39
    They're my 1st コーチ and they're even superior than I imagined they would be - I wish that I had bought oneyears ago! and they are very nice - I won't be able to wait to carry them! You pay for high quality and that is what you get!
  • Gravatar &#12467;&#12540;&#12481; September 25th, 2014 at 06:39
    It has witout a doubt torn and even insides have been released. Extremely dissatisfied on an &#12467;&#12540;&#12481;. 'm not ever buying and also presenting a great &#12467;&#12540;&#12481; once more!!!
  • Gravatar レイバン 激安 大阪 September 25th, 2014 at 21:02
     s . will not fritter away a more thoughts involving examination. the|in avoiding the|steer clear of the|cut|characteristics|attributes carefully|slice out-excuse the pun|prevent the} dividing start to your nearby clean. | induce might be overly wonderful. be sure to enable Web based mentor hand bags girl get!
  • Gravatar Mara G. Marlor September 26th, 2014 at 06:28
    Great post. I was checking continuously this blog and I am impressed!

    Extremely useful info specifically the last part :) I care for such information a lot.
    I was seeking this certain information for a long time.
    Thank you and good luck.
  • Gravatar Sue September 27th, 2014 at 14:56
    Your understanding of this subject matter is awesome. It actually
    touched me and I am glad I found this material.
    Thanks to you.
  • Gravatar prix dj soiree Bromont September 28th, 2014 at 00:13
    What's Going down i'm new to this, I stumbled upon this I've discovered It absolutely useful and
    it has helped me out loads. I hope to contribute & aid other customers like its
    aided me. Great job.
  • Gravatar tarif dj pour mariage Lac Megantic September 28th, 2014 at 00:50
    fantastic issues altogether, you simply received a new reader.
    What would you recommend in regards to your submit that you simply made a few days ago?
    Any positive?
  • Gravatar Nubia N. Robair September 29th, 2014 at 04:40
    Very nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts.
    After all I'll be subscribing to your feed and I hope you
    write again very soon!
  • Gravatar http://friendlyspectat75.snappages.com/ September 30th, 2014 at 01:33
    I really enjoyed reading this site, this is great blog.
  • Gravatar mk bags canada ebay September 30th, 2014 at 04:33
    Weeping cherries are prone to certain pest infestations, including scales, mites, caterpillars, borers, leaf rollers and aphids. The ones most likely to cause curling and discoloration of leaves are aphids and leaf rollers. Aphids damage the foliage by injecting a substance into the leaves that allows them to suck out the juices they ingest. This substance makes the leaves curl, protecting the feeding aphids from wind and rain. Leaf rollers are moth larvae that feed on the fruit, flowers and leaves of numerous fruit trees, including weeping cherries. In addition to leaf damage, these pests cause holes in fruit and wilted blossoms. Insecticides can reduce the population of these pests, although aphids may disappear without treatment, as area predators feed on these insects.
Gravatar