title: Sending Azure token to API back-end keeps returning 401 Unauthorzied error when OnTokenValidated is added to the API
body: <p>Recently we have created a React front-end which communicates with our API back-end following this tutorial: <a href="https://itnext.io/a-memo-on-how-to-implement-azure-ad-authentication-using-react-and-net-core-2-0-3fe9bfdf9f36" rel="nofollow noreferrer">https://itnext.io/a-memo-on-how-to-implement-azure-ad-authentication-using-react-and-net-core-2-0-3fe9bfdf9f36</a> </p>
  
  <p>Just as in the tutorial we have set-up the authentication in the front-end with the adal-react library. We added/registered the front-end in azure. </p>
  
  <p>Next we created our API (.Net Core 2) and also registered this in the azure environment, the config is setup in the appsettings:</p>
  
  <pre><code>"AzureAd": {
      "Instance": "https://login.microsoftonline.com/",
      "TenantDomain": "our_azure_environment.onmicrosoft.com",
      "TenantId": "our_azure_environment.onmicrosoft.com",
      "ClientId": "our_front-end_azure_id_1234"
    }
  </code></pre>
  
  <p>In the API we also added the JWT middleware in the <strong>ConfigureServices</strong> as follow:</p>
  
  <pre><code> services.AddAuthentication(sharedOptions =&gt;
               {
                   sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  
               })
               .AddJwtBearer(options =&gt;
               {
                   options.Audience = Configuration["AzureAd:ClientId"];
                   options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";
  
               });
  </code></pre>
  
  <p>When testing (calling an endpoint from the front-end) after logging in the front-end works, the data is being returned and the user is authenticated (api endpoint has the <code>Authorize</code> attribute), when not logged in the api endpoint returns 401 (as it should). </p>
  
  <p><strong>The problem is as follows:</strong>
  When I add the following piece of code to the API <strong>ConfigureServices</strong> (which I want to use to do some additional stuff after authenticating) :</p>
  
  <pre><code>options.Events = new JwtBearerEvents()
                   {
                       OnTokenValidated = context =&gt;
                       {
  
                           //Check if user has a oid claim
                           if (!context.Principal.HasClaim(c =&gt; c.Type == "oid"))
                           {
                               context.Fail($"The claim 'oid' is not present in the token.");
                           }
                           return Task.CompletedTask;
                       }
                   };
  </code></pre>
  
  <p>suddenly, the calls to the API endpoint return a <strong>401 (Unauthorized)</strong> error when logged in.. Though, if I remove the <code>OnTokenValidated</code> part it works fine.</p>
  
  <p>When reaching the <code>OnTokenValidated</code>, the token should already be validated / authenticated or am I wrong? 
  IntelliSense also says; <code>Invoked after the security token has passed validation and a ClaimsIdentity has been generated.</code></p>
  
  <p>Did I forgot to add some setting? My feeling tells me that it is propably a wrong setup in azure itself but I have actually no clue. </p>
  
  <p>The same token which is send from the front-end to the API is also being send to the graph API, when doing this, graph asks to give consent and after agreeing it works. With this in mind I believe I should add some permission to the API or something but I am not sure. </p>
  
  <p><strong>UPDATE</strong> </p>
  
  <p>juunas pointed out in his comment below that I was using the wrong  <code>ClaimsPrincipal value</code> this fixed the initial problem but now the following gave me the 401 error:</p>
  
  <p>In my <strong>ConfigureServices</strong> (before the <code>AddAuthentication</code> part) I have added the following to manage / add users to my AspNetUsers table (in my azure database):</p>
  
  <pre><code> services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
                  .AddEntityFrameworkStores&lt;TRSContext&gt;()
                  .AddDefaultTokenProviders();
  </code></pre>
  
  <p>When adding this code to the pipeline, I once more get the 401 error in the front-end. Any clue why this is? </p>
  
  <p><strong>UPDATE2</strong></p>
  
  <p>I found the solution for above (update). This was caused due to <code>AddIdentity</code> taken over the Authentication from JWT. This can be avoided by adding:</p>
  
  <ul>
  <li><code>Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;</code> </li>
  <li><code>Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;</code></li>
  </ul>
  
  <p>to <code>.AddAuthentication</code> options:</p>
  
  <pre><code>services.AddAuthentication(Options =&gt;
               {
                   Options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                   Options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; 
                   Options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; 
               })
  </code></pre>
  
  <p>More information about the above can be found here: 
  <a href="https://github.com/aspnet/Identity/issues/1376" rel="nofollow noreferrer">https://github.com/aspnet/Identity/issues/1376</a></p>