title: Azure Active Directory Authentication and SharePoint CSOM
body: <p>I have a web application, which connects to SharePoint (customer tenant) to create sites &amp; various List.</p>
  
  <p>To access the customers Sharepoint environment, I used <code>OpenIdConnectAuthenticationOptions</code> which prompts user for AAD creditinals and then the various options for which user wants to provide access ( This App and various API access needed is configured in AAD - when allowing access to "O365 SharePoint Online"</p>
  
  <p>Using <code>OpenIdConnectAutheticationOption</code>, on AuthorizationCode Received the code is used to get "AccessToken".
  Using this "AccessToken" to get clientContext gives error:</p>
  
  <blockquote>
    <p>"401 - Not authorized"</p>
  </blockquote>
  
  <p>How one can get the required token which allows CSOM operation?</p>
  
  <p>The code used from -
  <a href="https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-multitenant-openidconnect" rel="nofollow noreferrer">Active Directory Dot net Webapp Multitenant</a></p>
  
  <p>In the controller OnboardingController, Processcode function, after getting AcquireTokenByAuthorizationCodeAsync following code is used -</p>
  
  <pre><code>        string siteUrl = "https://svtestsite.sharepoint.com/sites/powerapps";
          ClientContext ctx = new ClientContext(siteUrl);
          ctx.ExecutingWebRequest +=
                       delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                       {
  webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                                             "Bearer " + result.AccessToken; // accessToken;
                 };
      ctx.Load(ctx.Web, p =&gt; p.Title);
      ctx.ExecuteQuery();
      Console.WriteLine(siteUrl);
      Console.WriteLine(ctx.Web.Title);
  </code></pre>