I have a (working) provider hosted app that mainly acts as a REST-Service (MVC5). I want to unit test my Rest-Controllers but can't find out how to give the right credentials.
I already got the URL including crucial parameters the following way:
private string GetBaseUrl(AppInstance myApp, string hostUrl)
{
string tokens = string.Format("SPHostUrl={0}&SPLanguage={1}&SPAppWebUrl={2}",
Uri.EscapeDataString(hostUrl), "en-US", Uri.EscapeDataString(myApp.AppWebFullUrl));
string url = myApp.StartPage;
url= url.Replace("{StandardTokens}", tokens);
string returnUrl = string.Format("{0}{{0}}?{1}", url.Split('?')[0], url.Split('?')[1]);
return returnUrl;
}
string hostUrl="http://mySp.sharepoint.com";
using (context = new ClientContext(hostUrl)) {
context.Credentials = new SharePointOnlineCredentials(Username, Password);
context.Load(context.Web);
context.ExecuteQuery();
var web = context.Web;
var addInInstance = AppCatalog.GetAppInstances(context, web);
addInInstance.Context.Load(addInInstance);
addInInstance.Context.ExecuteQuery();
var myApp = addInInstance.FirstOrDefault(app=>app.Title.ToLower().Contains("myApp"));
context.Load(mydeaApp);
context.ExecuteQuery();
string url=string.Format(GetBaseUrl(myApp, hostUrl),"/api/users";
// Returns something like "localhost://443400/api/users?SPHostUrl=http%3A%2F%2F...&SPAppWebUrl=http%3A%2F%2F...&SPLanguage=en-US"
}
url
contains something like "localhost://443400/api/users?SPHostUrl=http%3A%2F%2F...&SPAppWebUrl=http%3A%2F%2F...&SPLanguage=en-US
"
I did all this actions just because I needed the right Request-Parameters which are automatically generated when opening the app from inside sharepoint. If I call the Url using a httpRequest
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Credentials=new SharePointOnlineCredentials(Username, password);
var response = (HttpWebResponse)request.GetResponse()
it just does not work as expected. My App is called, but when debugging the app I can see that the spContext is just null (which does not happen when being called from within sharepoint).
When opening the same Url in a browser where I am not logged in the behaviour is the same. So I expect that this has to do something with credentials / userpermissions.