Hi @mc
what I want is to change the status code when it is not authorized.
Below is a way to override the default challenge logic in JwtBearerHandler.HandleChallengeAsync
, is to hook a handler to the JwtBearerEvents.OnChallenge
callback in builder.Services.AddAuthentication().AddJwtBearer()
:
builder.Services.AddAuthentication().AddJwtBearer("Bearer",options =>{
...
options .Events.OnChallenge = async context =>
{
// Call this to skip the default logic and avoid using the default response
context.HandleResponse();
// Write to the response in any way you wish
context.Response.StatusCode =202;
context.Response.Headers.Append("my-custom-header", "custom-value");
await context.Response.WriteAsync("You are not authorized! (or some other custom message)");
};
}
);
result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Qing Guo