title: Office 365 / EWS Authentication using OAuth
body: <p>I'm trying to log onto Office 365 Exchange Online using OAuth and EWS Managed API.</p>
  
  <p>I am able to use connect to the Office 365 Web API's (REST), so I do have a valid Token from the Active Directory Authentication Library (ADAL).</p>
  
  <p>Now, I'm trying to connect using EWS and TokenCredentials.</p>
  
  <p>The code is pretty easy, I think:</p>
  
  <pre><code>public static ExchangeService ConnectToServiceWithImpersonation(string token)
  {
      var service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
  
      if (true)
      {
          service.TraceListener = new TraceListener();
          service.TraceFlags = TraceFlags.All;
          service.TraceEnabled = true;
      }
  
      var credentials = new TokenCredentials(token);
  
      service.Credentials = credentials;
  
      service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
      return service;
  }
  </code></pre>
  
  <p>The token is generated by ADAL, which in turn is from sample code using the "Office 365 API Tools - Preview"</p>
  
  <pre><code>// Obtain information for communicating with the service:
  Office365ServiceInfo serviceInfo = Office365ServiceInfo.GetExchangeServiceInfo();
  if (!serviceInfo.HasValidAccessToken)
  {
      return Redirect(serviceInfo.GetAuthorizationUrl(Request.Url));
  }
  
  // Connect to Exchange
  var service = ConnectToServiceWithImpersonation(serviceInfo.AccessToken);
  
  Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
  </code></pre>
  
  <p>On the Folder.Bind call, I get a 401 Unauthorized error. EWS Trace gives me this:</p>
  
  <pre><code>2014-04-06 12:06:39.2012 TRACE ExchangeWebServices: EwsResponseHttpHeaders -&gt; &lt;Trace Tag="EwsResponseHttpHeaders" Tid="11" Time="2014-04-06 10:06:39Z"&gt;
  HTTP/1.1 401 Unauthorized
  request-id: 01ba1ca9-2850-480a-9d65-ec55bfef8657
  X-CasErrorCode: BadSamlToken
  X-FEServer: AMSPR04CA018
  Content-Length: 0
  Cache-Control: private
  Date: Sun, 06 Apr 2014 10:06:39 GMT
  Server: Microsoft-IIS/7.5
  WWW-Authenticate: Basic Realm=""
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  </code></pre>
  
  <p>Unfortunately, hours of googling did not really help, there does not seem to be very much specific information about EWS and OAuth authentication, and I have no idea how to further troubleshoot it, so I'm hoping that anyone has some advice on how to get it working.</p>