title: How to log "unauthorized" (401) response
body: <p>I'm using JWT tokens for authentication</p>
  
  <pre><code>services.AddAuthentication(options =&gt;
  {
      options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  })
      .AddJwtBearer(jwtOptions =&gt;
      {
          jwtOptions.TokenValidationParameters = tokenValidationParameters;
      });
  </code></pre>
  
  <p>In my controller then the <code>[Authorize]</code> attribute is used to ensure caller needs to be authenticated. This works fine. </p>
  
  <p>However: If a unauthorized user makes a request he gets a 401 response. Can I somehow "interupt" this response and log that an unauthorized call was made?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>A suggestion was to add an "exception middleware" I did so already but an unautorized call does not throw an exception...</p>
  
  <pre><code>services.AddMvc()
      .AddMvcOptions(options =&gt;
      {
          // Order is important! A request will run from top to bottom through each filter.
          options.Filters.Add(typeof(MyExceptionFilterAttribute));
      });
  </code></pre>
  
  <p>and the attribute:</p>
  
  <pre><code>public class MyExceptionFilterAttribute : ExceptionFilterAttribute
  {
      /// &lt;summary&gt;
      /// ctor
      /// &lt;/summary&gt;
      public MyExceptionFilterAttribute()
      {
  
      }
      /// &lt;summary&gt;
      /// 
      /// &lt;/summary&gt;
      /// &lt;param name="context"&gt;&lt;/param&gt;
      public override void OnException(ExceptionContext context)
      {
  
  
          ApplicationLogger.LogError("Bad request", context.Exception);
      }
  }
  </code></pre>