Thomas Raj
Thomas Raj

Reputation: 569

Authorize in ASP.NET CORE Web API

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.

Upvotes: 1

Views: 231

Answers (1)

Martin Devillers
Martin Devillers

Reputation: 17992

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();

Upvotes: 1

Related Questions