I've worked it out. From some reason, what the code above seems to do is it will use the user account of whoever installed the app in the first place... At least that what it seems like it's doing for me.
I've altered the code slight so I'm passing in the "UserAccessTokenForSPHost" value that you can get from the SharePointContext [SharePointContextProvider.Current.GetSharePointContext(HttpContext)], this will retrieve the user access token of the currently logged in user.
We can then use this token while creating our request object to communicate with SharePoint as the logged in user. Mainly, I updated the AddDocumentToLibrary function from
public void AddDocumentToLibrary(string documentName, string libraryName, string data, string sharePointUrl)
{
string newFormDigest = GetFormDigest(sharePointUrl);
string digestRequest = sharePointUrl + "/_api/web/GetFolderByServerRelativeUrl('/" + libraryName + "')/Files/add(url='" + documentName + "', overwrite=true)";
HttpWebRequest spNewRequest = (HttpWebRequest)HttpWebRequest.Create(digestRequest);
CredentialCache credNewCache = new CredentialCache();
credNewCache.Add(new Uri(digestRequest), "NTLM", CredentialCache.DefaultNetworkCredentials);
spNewRequest.Credentials = credNewCache;
spNewRequest.Method = "POST";
spNewRequest.Accept = "application/json;odata=verbose";
spNewRequest.ContentType = "application/json;odata=verbose";
spNewRequest.Headers.Add("X-RequestDigest", newFormDigest);
// For Content Length
byte[] postByte = Encoding.UTF8.GetBytes(data);
spNewRequest.ContentLength = postByte.Length;
Stream postStreamBody = spNewRequest.GetRequestStream();
postStreamBody.Write(postByte, 0, postByte.Length);
postStreamBody.Close();
HttpWebResponse webResponse = (HttpWebResponse)spNewRequest.GetResponse();
GetHTTPResponse(webResponse);
}
to be:
public void AddDocumentToLibrary(string documentName, string libraryName, string data, string sharePointUrl, string userAccessToken)
{
string newFormDigest = GetFormDigest(sharePointUrl);
string digestRequest = sharePointUrl + "/_api/web/GetFolderByServerRelativeUrl('/" + libraryName + "')/Files/add(url='" + documentName + "', overwrite=true)";
HttpWebRequest spNewRequest = (HttpWebRequest)HttpWebRequest.Create(digestRequest);
spNewRequest.Headers.Add("Authorization", "Bearer " + userAccessToken);
spNewRequest.Method = "POST";
spNewRequest.Accept = "application/json;odata=verbose";
spNewRequest.ContentType = "application/json;odata=verbose";
spNewRequest.Headers.Add("X-RequestDigest", newFormDigest);
// For Content Length
byte[] postByte = Encoding.UTF8.GetBytes(data);
spNewRequest.ContentLength = postByte.Length;
Stream postStreamBody = spNewRequest.GetRequestStream();
postStreamBody.Write(postByte, 0, postByte.Length);
postStreamBody.Close();
HttpWebResponse webResponse = (HttpWebResponse)spNewRequest.GetResponse();
GetHTTPResponse(webResponse);
}
Thank heavens this works now.