1

I have a console application to download a file from a SharePoint site. The sharepoint site uses claims based authentication.

This code throws a 403 Forbidden exception. The specified Network credential has full access to the site, and is able to download the same file from a browser.

WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential(username,Password,domain);
byte[] fileData = webClient.DownloadData(urlOfAFile); 
FileStream file = File.Create(localPath);
file.Write(fileData, 0, fileData.Length);

Any idea how to fix this?

ashwnacharya
  • 14,601
  • 23
  • 89
  • 112

2 Answers2

8

Maybe a bit late, but adding the right request header before making the request solves the problem:

webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
Mel Gerats
  • 2,234
  • 1
  • 16
  • 33
  • Hi, Thanks for answering. After adding your code snipped, I am getting a 401 Exception. Earlier, I was getting a 403 exception. Am I missing anything? – ashwnacharya Apr 05 '11 at 04:55
  • Are you trying to log in with Windows authentication or Forms authentication? – Mel Gerats Apr 06 '11 at 08:43
  • Hi @ashwnacharya Have you solved this problem? I also have the same problem, if you know how to solve it, can you post your answer here? Thanks! – nixjojo Apr 27 '12 at 07:53
  • This solution worked for me! I tried the [other solution](http://stackoverflow.com/questions/2316111/system-net-webclient-request-gets-403-forbidden-but-browsers-do-not-with-apache) provided in the same forum which did not work for me. – Vijay Sep 06 '12 at 07:11
  • I had to add the user agent header also and then it worked. _SPWebClient.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)"; – EthR Nov 29 '16 at 14:32
0

I also encounter this issue, and below is my research:

{
  ClientContext m_clientContext = new ClientContext(strSiteUrl);
    m_clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(ctx_MixedAuthRequest);
    m_clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
    m_clientContext.Credentials = new NetworkCredential(uname, pwd);
    Web m_currentWeb = m_clientContext.Web;
    m_clientContext.Load(m_currentWeb);
    m_clientContext.ExecuteQuery();
}

  private void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e)
    {
        try
        {
            //Add the header that tells SharePoint to use Windows authentication.
            e.WebRequestExecutor.RequestHeaders.Add(
            "X-FORMS_BASED_AUTH_ACCEPTED", "f");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error setting authentication header: " + ex.Message);
        }
    }

here is the article: https://msdn.microsoft.com/en-us/library/office/hh124553(v=office.14).aspx

Emily
  • 1