I'm having trouble getting OAuth credentials to work with EWS in Office 365. At a high level I'm writing a SharePoint 2013 app and I'm trying to access the user's mailbox data in Exchange. I did verify my EWS code is 'correct' by swapping out the OAuth code for a hard coded username and password and it worked perfectly.
I get a token back using the code below, however I'm getting a 401 when I try to get the access the user's inbox. I left it off for brevity, but I am passing the token into a new OAuthCredentials object before accessing the inbox.
string acsUrl = "https://accounts.accesscontrol.windows.net/";
using (WebClient exchangeTokenClient = new WebClient())
{
exchangeTokenClient.BaseAddress = acsUrl;
NameValueCollection requestParams = new NameValueCollection();
requestParams.Add("grant_type", "client_credentials");
requestParams.Add("client_id", "<clientid>@<realm>");
requestParams.Add("client_secret", "<client secret>");
requestParams.Add("resource", "00000002-0000-0ff1-ce00-000000000000/outlook.office365.com@<realm>");
exchangeTokenClient.Headers.Add("Authorization", "Bearer " + ((SharePointAcsContext)spContext).UserAccessTokenForSPAppWeb);
byte[] responseBytes = exchangeTokenClient.UploadValues("<realm>/tokens/OAuth/2", "POST", requestParams);
string response = Encoding.UTF8.GetString(responseBytes);
}
The more that I think about this, the more I wonder if my 'app' needs rights on the exchange server and if that is what the root cause of the 401 is.
Has anyone actually done this? I feel like it should be possible, but I can't seem to find a lot of documentation on the process.
Thanks
Joe