Authorize in ASP.NET CORE Web API

Viewed 82

I have added [Authorize] attribute over my BaseController. Without JWT token it shows 401 error, I need to customize that 401 error. I need to understand at which place the Application throws 401 error. Can someone please help me.

1 Answers

There are several ways to customize this behavior, but I think the most straightforward one is to write a custom middleware.

// Startup.Configure method

app.UseRouting();

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
    {
        await context.Response.WriteAsync("Token Validation Has Failed. Request Access Denied");
    }
});

app.UseAuthentication();

app.UseAuthorization();

app.UseEndpoints();

Related