Home > database >  Middleware not returning error details to API request
Middleware not returning error details to API request

Time:01-29

I have a API project in asp.net core and I have a middleware that handle JWT authentication.

This is the method that validates the token

private void attachAccountToContext(HttpContext context, string token)
        {
            try
            {
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                byte[] encodedKey = Encoding.ASCII.GetBytes(_configuration["JWTSecretKey"]);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey = new SymmetricSecurityKey(encodedKey),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);
            }
            catch (Exception ex)
            {
                throw new HttpRequestException(ex.Message);
            }

If the token is expired I get a message in console and inside the catch statement, but when I make the request from Postman, after publishing the project, it returns error 500 no matter what I throw.

I would like to return the error message to the client but I don't know how to pass it out the middleware

CodePudding user response:

When you get an error in development environment, this error will be shown. After publishing your app, these pure error messages should be hidden from client side for security purposes. But, you can write your own exception middleware for return exception to client side without security risk for only information purposes;

    public class ExceptionMiddleware
    {
        private RequestDelegate _next;

        public ExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception e)
            {
                await HandleExceptionAsync(httpContext, e);
            }
        }

        private Task HandleExceptionAsync(HttpContext httpContext, Exception e)
        {
            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            return httpContext.Response.WriteAsync(new ErrorDetails
            {
                StatusCode = httpContext.Response.StatusCode,
                Message = e.Message
            }.ToString());
        }
    }

Then you have to register it to IApplicationBuilder as a extension method

public static class ExceptionMiddlewareExtensions
{
     public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
     {
         app.UseMiddleware<ExceptionMiddleware>();
     }
}

Then you have to register it inside of Startup.cs -> Configure method as a:

   app.ConfigureCustomExceptionMiddleware();

After these configurations any threw exception will be returned to client side with message and status code.

  •  Tags:  
  • Related