Code to download files from a SharePoint 2010 site using Claims Based Authentication


Trying to download some images from a SharePoint 2010 Image Library using code I was getting HPPT Status 401 – Unauthorized.

First thing I check was the user name and password in a browser window. It worked just fine.

This code used to work for SharePoint 2007 but then I recalled the site uses Claims Based Authentication and it needs a little change in order to authenticate a user on 2010.

Checking the definitions for Windows Authentication requests on SharePoint 2010 I saw we need to specify the X-FORMS_BASED_AUTH_ACCEPTED and the user agent HTTP headers .

Follow a code snippet:

string url = @"File URL";
string userName = "account";
string password = "password";
string domain = "domain";


NetworkCredential credential = new NetworkCredential(userName, password, domain);
WebClient client = new WebClient();
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
client.Credentials = credential;
byte[] data = client.DownloadData(url);


After this code change it worked just fine.

See you,

Amadeu.

Advertisements

7 Responses to Code to download files from a SharePoint 2010 site using Claims Based Authentication

  1. zhongyue1982 says:

    I follow your way and got error: The remote server returned an error: (401) Unauthorized.

  2. zhongyue1982 says:

    I follow your code but got this error: The remote server returned an error: (401) Unauthorized.

    I can login use IE like this:
    Username: domain\username
    Password: 123456

    My code like this:
    string userName = “username”;
    string password = “123456”;
    string domain = “domain”;
    doesn’t work,

    Like this also doesn’t work:
    string userName = @”domain\username”;
    string password = “123456”;

  3. Renato Suon says:

    Great site, thanks for share this article with us

  4. pdfcast.org says:

    Hello There. I found your blog using msn. This is a very well written article.
    I will be sure to bookmark it and come back to read more of your useful info.

    Thanks for the post. I will certainly comeback.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: