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?