title: Sending Response body in JwtBearerEvents.OnAuthenticationFailed
body: <p>I have a .NET Core 2.0 application using OAuth Bearer Auth with an Azure AD V2 endpoint. I want to the exception message to be returned to the user if there is a 500 error. I have the following code to do that:</p>
  
  <pre><code>            options.Events = new JwtBearerEvents
              {
                  // This used to be options.Notifications = new OpenIdConnectAuthenticationNotifications
                  OnTokenValidated = AzureAdAuthCallbacks.TokenValidated,
                  OnAuthenticationFailed = async context =&gt;
                  {
                      context.Response.ContentType = "text/plain";
                      await context.Response.WriteAsync(context.Exception.Message);
                  }
              };
          }
  </code></pre>
  
  <p>When validation fails, that code does execute, but the response dosn't get returned. I get <a href="https://pastebin.com/fSK1xMsP" rel="noreferrer">a stack trace</a>. </p>
  
  <p>This is the message:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: StatusCode cannot be set because the response has already started.</p>
  </blockquote>
  
  <p>With this line of note:</p>
  
  <blockquote>
    <p>at WebCsProj.Infrastructure.RequestMetadataMiddelware.&lt;>c.&lt;b__0_0>d.MoveNext() in C:\Users\justin.dearing\source\repos\my-solution\WebCsProj\Infrastructure\RequestMetadataMiddelware.cs:line XXX</p>
  </blockquote>
  
  <p>However, that piece of middleware finishes successfully:</p>
  
  <pre><code>public static class RequestMetadataMiddelware
  {
      public static IApplicationBuilder UseRequestMetadataExtractor(this IApplicationBuilder app)
      {
          return app.Use(async (context, next) =&gt;
          {
              // I don't set a status code here.
              // Some code that works is here
              await next.Invoke(); // The debugger indicates the code makes it here:
          });
      }
  }
  </code></pre>
  
  <p>What can I do to debug this or what is the right way to set the response? Is there a way to stop the middle-ware chain from executing in <code>OnAuthenticationFailed</code>?</p>