Access SharePoint online using client object model- Forbidden error - c#

I tried to Create a new list item using client object model. I have created an asp.net application to do the task. It works if I pass the URL of SharePoint server which is installed in my machine.
But if I give my SharePoint online URL it is not working as below code shows. I get "The remote server returned an error: (403) Forbidden. " error.
Any idea?
ClientContext context = new ClientContext("https://xxx.sharepoint.com/SitePages/");
List announcementsList = context.Web.Lists.GetByTitle("Announcements");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem newItem = announcementsList.AddItem(itemCreateInfo);
newItem["Title"] = result.City;
newItem["Body"] = result.State;
newItem.Update();
context.ExecuteQuery();

if you are trying to get a Context object from SharePoint Online you have to put in the right Credentials, as for SharePoint Online you should use the SharePointOnlineCredentials Class
A possible Authentication Method can be look like this:
private void AutheticateO365(string url, string password, string userName)
{
Context = new ClientContext(url);
var passWord = new SecureString();
foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
Context.Credentials = new SharePointOnlineCredentials(userName, passWord);
var web = Context.Web;
Context.Load(web);
Context.ExecuteQuery();
}

I would imagine you just have to supply your login credentials and it should work:
clientContext.Credentials = new NetworkCredential("Username", "Password", "Domain");
You'll need to including System.Net:
using System.Net;

Related

SharePoint Login Credential

Currently I try to developed application by using SharePoint that retrieve data from List
Now I try to developed for Login Function, The error display as Below
The underlying connection was closed: An unexpected error occurred on a send.
Here with my Source Code
string WebUrl = "https://xxx.sharepoint.com/sites/devspace";
string username = txtUsername.Text;
string pwd = txtPassword.Text;
ClientContext context = new ClientContext(WebUrl);
Web web = context.Web;
SecureString passWord = new SecureString();
foreach (char c in pwd.ToCharArray())
passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(username, passWord);
try
{
context.Load(web);
context.ExecuteQuery();
lblStatus.Text = "Olla " + web.Title;
}catch(Exception ex)
{
lblStatus.Text = ex.Message.ToString();
}
Any suggestion for this? Thank in advanced.
Updated:
I'm using SharePoint 2016, login via Windows Server AD.
As discussed, you are using SharePoint 2016, then please download and install CSOM with SharePoint 2016 version Nuget package not SharePoint Online:
Microsoft.SharePoint2016.CSOM
And use this code snippet:
ClientContext clientContext = new ClientContext("https://example.com/sites/testsite/");
clientContext.Credentials = new NetworkCredential("user", "password", "domain");
// Get the SharePoint web
Web web = clientContext.Web;
// Get the SharePoint list collection for the web
ListCollection listColl = web.Lists;
// Retrieve the list collection properties
clientContext.Load(listColl);
// Execute the query to the server.
clientContext.ExecuteQuery();
// Loop through all the list
foreach (List list in listColl)
{
// Display the list title and ID
Console.WriteLine("List Name: " + list.Title + "; ID: " + list.Id);
}
Console.ReadLine();
SharePoint 2016 On Premise not need to use SharePointOnlineCredentials class, just pass username, password, domain as code snippet above.

Access denied when downloading file from Sharepoint CSOM

I am trying to download a file from a client Sharepoint site. I am using sharepoint CSOM.
My code is as follows:
using Microsoft.SharePoint.Client;
var username = "username";
var password = "pass";
var url = "https://myclient.sharepoint.com/";
var fileurl = "https://myclient.sharepoint.com/teams/folder1/folder%20x/somefile.docx";
using (ClientContext context = new ClientContext(url))
{
SecureString passWord = new SecureString();
foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials(username, passWord);
Uri filename = new Uri(fileurl);
string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
string serverrelative = filename.AbsolutePath;
Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(serverrelative);
context.Load(file);
ClientResult<Stream> streamResult = file.OpenBinaryStream();
context.ExecuteQuery();
var file2 = streamResult.Value;
}
The problem is that I get access denied, yet when I log in with the same credentials, I can download the file successfully.
Is there a separate permission in Sharepoint for downloading file from API instead of UI?
Could the space in the folder name be the problem?
UPDATE
Verified this does not have anything to do with spaces in folder or filename.
In case if SharePoint site uses multiple authentication providers using a set of Windows credentials (also relevant for SharePoint Online), the additional header must be included in a request: X-FORMS_BASED_AUTH_ACCEPTED with a value of f
For ClientContext class the header could be included like this:
ctx.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.WebRequest.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f";
};
Example
var file = ctx.Web.GetFileByUrl(fileAbsUrl);
ctx.Load(file);
var streamResult = file.OpenBinaryStream();
ctx.ExecuteQuery();
//save into file
using (var fileStream = System.IO.File.Create(#"C:\path\filename.docx"))
{
streamResult.Value.Seek(0, SeekOrigin.Begin);
streamResult.Value.CopyTo(fileStream);
}
Note: instead of converting to relative url, GetFileByUrl
method is used which accepts absolute url
Problem was that I was not connecting to the right url (new ClientContext(url))
I was connecting to: https://myclient.sharepoint.com/
I should have been connecting to: https://myclient.sharepoint.com/teams/folder1/

TFS Server Credential Error

I want to collect a List of Project in TFS 2013 Using API .
I am Putting URL and User name and Password, (Server properly Connected Browser).
I have collected all Project with TFS Collection List. But my API Call does not working on client. What is the problem?
Here My Sample Code
Uri configurationServerUri = new Uri(URL);
NetworkCredential credentials = new NetworkCredential(UserName, Password);
teamProjectCollection = new TfsTeamProjectCollection(configurationServerUri, credentials);// Set Connection
teamProjectCollection.EnsureAuthenticated();
//CatalogNode configurationServerNode = teamProjectCollection.TeamFoundationServer.TfsTeamProjectCollection.CatalogNode;
//li.Add(configurationServerNode.Resource.DisplayName);
TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
ITeamProjectCollectionService tpcService = configurationServer.GetService<ITeamProjectCollectionService>();
foreach (TeamProjectCollection tpc in tpcService.GetCollections())
{
list.Add(tpc.Name);
}

Connecting to Sharepoint Online returns 401: Unauthorized

I am trying to perform a Sharepoint Online search using the C# API:
var clientContext =
new ClientContext("https://foobar.sharepoint.com/_layouts/15/start.aspx#/Shared%20Documents");
var pw = "apassword";
var secure = new SecureString();
foreach (var c in pw) secure.AppendChar(c);
var credentials = new SharePointOnlineCredentials("adress#mail.com", secure);
clientContext.Credentials = credentials;
var keywordQuery = new KeywordQuery(clientContext);
keywordQuery.QueryText = "SharePoint";
var searchExecutor = new SearchExecutor(clientContext);
var results = searchExecutor.ExecuteQuery(keywordQuery);
clientContext.ExecuteQuery();
I get the response '401: Unauthorized', although the credentials I've provided are correct. What am I missing here?
You are trying to connect to a SharePoint document library (https://foobar.sharepoint.com/_layouts/15/start.aspx#/Shared%20Documents). Try to connect to "https://foobar.sharepoint.com/".
Also the client context might not have enough permissions to perform the search.

Getting Access Denied on sharepoint list

I'm making an ASMX web method call that contains the following code...It ultimately adds a new item to a sharepoint list
string spsite = "http://site/subsite";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite objSite = new SPSite(spsite))
{
using (SPWeb oweb = objSite.OpenWeb())
{
oweb.AllowUnsafeUpdates = true;
SPList list = oweb.Lists["List"];
SPListItem item = list.Items.Add();
item["col1"] = "test";
item["col2"] = "test";
item.Update();
}
}
});
However, I get the following error messages...
You do not have permission to view this directory or page using the credentials that you supplied
Why is this? I thought RunWithElevatedPrivileges does away with this?
Where is this web service hosted? Using RunWithElevtatedPrivileges will use the account that the app pool runs on. If the app pool does not have permission, then you will get access denied.

Categories