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

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

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 while working with SharePoint 2013 Online Site using C#.Net Client object model code
The remote server returned an error 403 forbidden while working with SharePoint 2013 Online Site using C#.Net Client object model code

Also read:
Get user permissions for a site using CSOM in SharePoint Online

Get Profile picture url from User Information List using SharePoint 2013 server object model

SharePoint 2013 SPListItem method Update SystemUpdate and UpdateOverwriteVersion

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)

{

}

Solution:
Here we need to write handle authentication using SharePointOnlineCredentials like below:
SecureString passWord = new SecureString();

foreach (char c in “Qwe@54321”.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.

Hope this will be helpful.


You May Also like the Following SharePoint Online Tutorials:

About 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 SharePointSky.com

View all posts by Bijay Kumar →