Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Returning 401 and JSON #699

Closed
Closed
@bragma

Description

@bragma

Hi,
I'm using UseJwtBearerAuthentication. On a failed authentication (ex: expired token), the middleware throws and exception causing the server to return 500. I'd like instead to return 401 and a JSON explaining the problem.
I'm not sure I've understood the "OnAuthenticationFailed" event, but I've not been able to do anything from there. So, I've resolved to "UseExceptionHandler" and I've been able to intercept Security related Exceptions, but I am not sure on how to allow other exception types to be handled by the default error handler, such as "UseDeveloperExceptionPage".

My setup is:

app.UseExceptionHandler(appBuilder =>
{
    appBuilder.Use(async (context, next) =>
    {
        var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;

        if (error != null && error.Error is SecurityTokenExpiredException)
        {
            // Send expired response
        }
        else if (error != null && error.Error is SecurityTokenInvalidSignatureException)
        {
            // Send bad signature response
        }
        else if (error != null && error.Error != null)
        {
            // Another exception type. How to let it pass through so it's caught by UseDeveloperExceptionPage?
        }
        else
        {
            await next();
        }
    });
});

Is this the suggested way of handling Security exceptions?
Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions