title: Authenticate an EWS application by using OAuth
body: <p>I was trying to follow the steps from this <a href="https://msdn.microsoft.com/en-us/library/office/dn903761(v=exchg.150).aspx" rel="nofollow">this</a> tutorial to authenticate my app by oAuth and use the retrieved token for EWS managed API. </p>
  
  <p>Here is the final code:</p>
  
  <pre><code>static void Run()
          {
              string authority = ConfigurationSettings.AppSettings["authority"];
              string clientID = ConfigurationSettings.AppSettings["clientID"];
              Uri clientAppUri = new Uri(ConfigurationSettings.AppSettings["clientAppUri"]);
              string serverName = ConfigurationSettings.AppSettings["serverName"];
  
              AuthenticationResult authenticationResult = null;
              AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
  
  
              string errorMessage = null;
              try
              {
                  Console.WriteLine("Trying to acquire token");
                  authenticationResult = authenticationContext.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto);
              }
              catch (AdalException ex)
              {
                  errorMessage = ex.Message;
                  if (ex.InnerException != null)
                  {
                      errorMessage += "\nInnerException : " + ex.InnerException.Message;
                  }
              }
              catch (ArgumentException ex)
              {
                  errorMessage = ex.Message;
              }
  
              if (!string.IsNullOrEmpty(errorMessage))
              {
                  Console.WriteLine("Failed: {0}" + errorMessage);
                  return;
              }
  
              Console.WriteLine("\nMaking the protocol call\n");
              ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
              exchangeService.Url = new Uri(serverName + "ews/exchange.asmx");
              exchangeService.TraceEnabled = true;
              exchangeService.TraceFlags = TraceFlags.All;
              exchangeService.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
              //exchangeService.TraceListener = new TraceListener();
              var res = exchangeService.FindFolders(WellKnownFolderName.Root, new FolderView(10));
          }
  </code></pre>
  
  <p>and here is the configuration file:</p>
  
  <pre><code>    &lt;add key="authority" value="https://login.windows.net/???.onmicrosoft.com" /&gt;
      &lt;add key="clientId" value="???" /&gt;
      &lt;add key="clientAppUri" value="https://localhost/8a4abb13c70dab64a18ae81089bc2cff"/&gt;
      &lt;add key="serverName" value="https://outlook.office365.com/" /&gt;
  </code></pre>
  
  <p>Here is the error message:</p>
  
  <pre><code>The request failed. The remote server returned an error: (401) Unauthorized.
  </code></pre>
  
  <p>and here is trace of ExchangeService:</p>
  
  <pre><code>&lt;Trace Tag="EwsRequestHttpHeaders" Tid="12" Time="2015-08-13 13:56:24Z"&gt;
  POST /ews/exchange.asmx HTTP/1.1
  Content-Type: text/xml; charset=utf-8
  Accept: text/xml
  User-Agent: ExchangeServicesClient/15.00.0847.030
  Accept-Encoding: gzip,deflate
  Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlMzY1LmNvbS8iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9mMTFjYjAzOS05NzFlLTQxOWItYjg5NS01ZjIxZTkxOWFlZmUvIiwiaWF0IjoxNDM5NDczOTI0LCJuYmYiOjE0Mzk0NzM5MjQsImV4cCI6MTQzOTQ3NzgyNCwidmVyIjoiMS4wIiwidGlkIjoiZjExY2IwMzktOTcxZS00MTliLWI4OTUtNWYyMWU5MTlhZWZlIiwiZW1haWwiOiJoYW1pZC5lbG1pQGNvbnNldHRvLmNvbSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2JiZDIwM2I4LTkwMjEtNDZiZi05NzE2LTUyZWE5MzY1MjQ3Zi8iLCJhbHRzZWNpZCI6IjU6OjEwMDNCRkZEOEIxMTQxMTUiLCJzdWIiOiJPc0t2cnY3YU1hX3VKZktYNGltYXduSVp6SVIybDdkTXBkcUV6M0Y2U2U0IiwiZ2l2ZW5fbmFtZSI6IkhhbWlkIiwibmFtZSI6IkhhbWlkIEVsbWkiLCJhbXIiOlsicHdkIl0sInVuaXF1ZV9uYW1lIjoiaGF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lt;/Trace&gt;
  &lt;Trace Tag="EwsRequest" Tid="12" Time="2015-08-13 13:56:24Z" Version="15.00.0847.030"&gt;
    &lt;?xml version="1.0" encoding="utf-8"?&gt;
    &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;
      &lt;soap:Header&gt;
        &lt;t:RequestServerVersion Version="Exchange2013" /&gt;
      &lt;/soap:Header&gt;
      &lt;soap:Body&gt;
        &lt;m:FindFolder Traversal="Shallow"&gt;
          &lt;m:FolderShape&gt;
            &lt;t:BaseShape&gt;AllProperties&lt;/t:BaseShape&gt;
          &lt;/m:FolderShape&gt;
          &lt;m:IndexedPageFolderView MaxEntriesReturned="10" Offset="0" BasePoint="Beginning" /&gt;
          &lt;m:ParentFolderIds&gt;
            &lt;t:DistinguishedFolderId Id="root" /&gt;
          &lt;/m:ParentFolderIds&gt;
        &lt;/m:FindFolder&gt;
      &lt;/soap:Body&gt;
    &lt;/soap:Envelope&gt;
  &lt;/Trace&gt;
  A first chance exception of type 'System.Net.WebException' occurred in System.dll
  &lt;Trace Tag="EwsResponseHttpHeaders" Tid="12" Time="2015-08-13 13:56:26Z"&gt;
  HTTP/1.1 401 Unauthorized
  request-id: ea025c98-9e74-4799-8ac2-77251f641912
  X-CalculatedBETarget: HE1PR09MB0330.eurprd09.prod.outlook.com
  X-BackEndHttpStatus: 401
  Content-Length: 0
  Set-Cookie: ClientId=4HGSRI510SWOAIFT0U31G; expires=Fri, 12-Aug-2016 13:57:17 GMT; path=/; secure; HttpOnly,exchangecookie=86f12da3fb89403bb91c5fe8b525f43d; expires=Sat, 13-Aug-2016 13:57:18 GMT; path=/; HttpOnly,ClientId=4HGSRI510SWOAIFT0U31G; expires=Fri, 12-Aug-2016 13:57:17 GMT; path=/; secure; HttpOnly
  Server: Microsoft-IIS/8.0
  x-ms-diagnostics: 2000001;reason="No applicable user context claims found.";error_category="invalid_token"
  X-DiagInfo: HE1PR09MB0330
  X-BEServer: HE1PR09MB0330
  X-Powered-By: ASP.NET
  X-FEServer: DB5PR09CA0061
  WWW-Authenticate: Bearer client_id="00000002-0000-0ff1-ce00-000000000000", trusted_issuers="00000001-0000-0000-c000-000000000000@*", token_types="app_asserted_user_v1", authorization_uri="https://login.windows.net/common/oautA first chance exception of type 'Microsoft.Exchange.WebServices.Data.ServiceRequestException' occurred in Microsoft.Exchange.WebServices.dll
  h2/authorize", error="invalid_token",Basic Realm="",Basic Realm=""
  Date: Thu, 13 Aug 2015 13:57:17 GMT
  
  
  &lt;/Trace&gt;
  </code></pre>
  
  <p>Any idea would be greatly appreciated.</p>