Reputation: 1093
I am trying to create a web application (ASP.NET MVC with C#) that allows a user to upload files to a SharePoint Online site.
This code works when in SharePoint online only if I use my actual email and password.
using (ClientContext context = new ClientContext(url))
{
var password = new SecureString();
foreach(var c in "password")
{
password.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(email, password);
//code to upload file
}
But I do not want to use my credential for all the users of this web application. So, I've been doing some research on this and found about the Claim-based authentication. https://code.msdn.microsoft.com/Remote-Authentication-in-b7b6f43c#content
I'll definitely try this, but I'm still wondering if this is the only way to achieve what I want to do. The web application authenticates users with windows authentication, and so does the sharepoint online site. Is it really true that there's no way for the sharepoint online site to get the credential from the web application?
Upvotes: 3
Views: 6218
Reputation: 2091
We can get Access token to upload file via REST API, here is an article for your reference: SharePoint Online remote authentication (and Doc upload)
About how to Upload file to document via CSOM, here is a demo for your reference:
/// <summary>
/// upload file to document library
/// </summary>
/// <param name="siteUrl">http://sp/sites/DevSite</param>
/// <param name="filePath">C:\\</param>
/// <param name="fileName">hello2.txt</param>
/// <param name="docLibName">MyDocLib</param>
public static void uploadFile(string siteUrl, string filePath, string fileName, string docLibName)
{
siteUrl = siteUrl.EndsWith("/") ? siteUrl.Substring(0, siteUrl.Length - 1) : siteUrl;
ClientContext context = new ClientContext(siteUrl);
List docLib = context.Web.Lists.GetByTitle(docLibName);
context.Load(docLib);
context.ExecuteQuery();
Byte[] bytes = System.IO.File.ReadAllBytes(filePath + fileName);
FileCreationInformation createFile = new FileCreationInformation();
createFile.Content = bytes;
createFile.Url = siteUrl + "/" + docLibName + "/" + fileName;
createFile.Overwrite = true;
Microsoft.SharePoint.Client.File newFile = docLib.RootFolder.Files.Add(createFile);
newFile.ListItemAllFields.Update();
context.ExecuteQuery();
}
Upvotes: 1