The remote server returned an error 403 forbidden while working with SharePoint 2013 Online Site using C#.Net Client object model code

This SharePoint tutorial, we will discuss how to solve The remote server returned an error 403 forbidden error which comes in CSOM SharePoint Online.

Recently while working with SharePoint Online using.Net managed object model code I got the below error which says:

An unhandled exception of type ‘System.Net.WebException’ occurred in Microsoft.SharePoint.Client.dll
Additional information: The remote server returned an error: (403) Forbidden.

The remote server returned an error 403 forbidden
The remote server returned an error 403 forbidden

Here I was trying to write code like below:

ClientContext clientContext = new ClientContext(“https://onlysharepoint2013.sharepoint.com/”);
Web web = clientContext.Web;

try
{
file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
clientContext.Load(file);
clientContext.ExecuteQuery();
}

catch (ServerException ex)
{

}

The remote server returned an error 403 forbidden

Here we need to write handle authentication using SharePointOnlineCredentials like below:

SecureString passWord = new SecureString();
foreach (char c in “*******”.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(“user1@OnlySharePoint2013.onmicrosoft.com”, passWord);

So the full code will look like below:

ClientContext clientContext = new ClientContext(“https://onlysharepoint2013.sharepoint.com/”);
SecureString passWord = new SecureString();
foreach (char c in “YourPasword”.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(“Username@OnlySharePoint2013.onmicrosoft.com”, passWord);
Web web = clientContext.Web;

try
{
file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
clientContext.Load(file);
clientContext.ExecuteQuery();
}

catch (ServerException ex)
{
}

Now you will not receive any error.

You may like following SharePoint CSOM tutorials:

Hope this will be helpful to resolve “The remote server returned an error 403 forbidden” error in SharePoint.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SPGuides.com

>