Tip 43 – How to authenticate against a Data Service

Problem:

When writing code against a Data Service, like say SharePoint, the client application must provide a valid set of credentials, or you will see a dreaded “401 Unathorized” response.

For Silverlight applications hosted on the same site as the DataService, this is generally handled for you automatically.

But WPF applications, for example, need manual intervension.

Solution:

The solution it to set the Credentials property on your DataServiceContext before you issue any queries or updates, like this:

Uri uri = new Uri("https://mflasko-dev/_vti_bin/listdata.svc"));
TeamSiteDataContext ctx = new TeamSiteDataContext(uri);
ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;

That’s it.

Done.

Of course you can get fancy and provide another set of credentials if necessary, but generally the DefaultCredentials is what you want.