0
votes

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

2

2 Answers

1
votes

Part #1: Hi Joe, you can't quite do it this way. It seems you try to re-play a SharePoint token to the Exchange endpoint. Exchange will reject the SharePoint token, as the token is not for the Exchange endpoint (it fails the audience check).

Now to get it to work if you want to do Auth the only way for Exchange is to use the new OAuth2 model we announced at SPC. You can get more details from my session presentation at "http://www.sharepointconference.com/content/sessions/SPC379" (I believe we post the slides in a few days). There are three documents out there that I can also recommend to take a look, that is: Authentication and authorization using Common Consent Framework: "http://msdn.microsoft.com/en-us/library/dn605895(v=office.15).aspx", ...

1
votes

Part #2 ... How to: Integrate O365 with a web server app using Common Consent Framework at "http://msdn.microsoft.com/en-us/library/dn605894(v=office.15).aspx" and "Using the Mail, Calendar, and Contact REST APIs to work with emails, calendar items, and contacts" at "http://msdn.microsoft.com/en-us/library/dn605896(v=office.15).aspx"

Hope this helps,

Cheers! Matthias