title: OAuth Authentication to EWS
body: <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>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", "&lt;clientid&gt;@&lt;realm&gt;");
  requestParams.Add("client_secret", "&lt;client secret&gt;");
  requestParams.Add("resource", "00000002-0000-0ff1-ce00-000000000000/outlook.office365.com@&lt;realm&gt;");
  exchangeTokenClient.Headers.Add("Authorization", "Bearer " + ((SharePointAcsContext)spContext).UserAccessTokenForSPAppWeb);
  
  byte[] responseBytes = exchangeTokenClient.UploadValues("&lt;realm&gt;/tokens/OAuth/2", "POST", requestParams);
  
  string response = Encoding.UTF8.GetString(responseBytes);
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>Thanks</p>
  
  <p>Joe</p>