0

I have an ASP.NET Core web application which makes use of Microsoft's AuthenticationMiddleware.

I configure this on startup.

 app
    .UseMiddleware<ExceptionHandlingMiddleware>()
    .UseAuthentication()
    .UseMvc();

The authentication being used is Bearer Authentication. I have a JWT token validator class which inherits from ISecurityTokenValidator.

I register this in ConfigureServices:

services.AddSingleton<ISecurityTokenValidator, JwtTokenValidator>();

var serviceProvider = services.BuildServiceProvider();
var myTokenValidator = serviceProvider.GetService<ISecurityTokenValidator>();

services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
    options.SecurityTokenValidators.Add(myTokenValidator);
});

Upon request to the web app the ValidateToken method of this JwtTokenValidator class is called.

However if this method throws an exception (say if the token is malformed) it is not caught by my exception handling middleware. Implemented similarly to how this answer suggests. My exception handler class is registered before the Microsoft-UseAuthentication and does work for any other exceptions thrown in middleware.

Instead the web app just returns a 401 unauthorized with no body.

I want to add a custom JSON blog within this response to provide slightly more detail to callers of my api. How can this be done?

Michael Hancock
  • 2,673
  • 1
  • 18
  • 37
  • It's an aside to your question, but do you really need to add `ISecurityTokenValidator` to DI here? It's a [bad idea](https://stackoverflow.com/questions/56042989/what-are-the-costs-and-possible-side-effects-of-calling-buildserviceprovider-i/56058498#56058498) to use `BuildServiceProvider` within `ConfigureServices` like that. – Kirk Larkin May 15 '19 at 15:49
  • It could certainly be moved out, this wasn't something I was aware of. Thanks @KirkLarkin – Michael Hancock May 15 '19 at 16:01
  • No worries. For the problem itself, you should look at [`JwtBearerEvents.OnChallenge`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents.onchallenge?view=aspnetcore-2.2) and *maybe* [`JwtBearerEvents.OnAuthenticationFailed`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents.onauthenticationfailed?view=aspnetcore-2.2). – Kirk Larkin May 15 '19 at 16:11
  • 1
    Great suggestion, using `OnAuthenticationFailed` I was able to inspect the exception that was thrown in `JwtTokenValidator` and handle it there. At which point I could rethrow it for handling in my exception handling middleware. – Michael Hancock May 16 '19 at 08:18

0 Answers0