Search code examples
openiddict

OpenIddict - Customise Invalid Token response to include a JSON body


If I send a request into my API with an invalid access token, I get the following response:

Base Address:              https://localhost:54701/
Token Expired:             True
IsSuccessStatusCode:       False
Status:                    Unauthorized
StatusCode:                401
WwwAuthenticate:           Bearer error="invalid_token", error_description="The specified 
                           token is invalid.", error_uri="https://documentation.openiddict.com/errors/ID2004"
ReasonPhrase:              Unauthorized
ContentType:            
ContentLength:             0
Content:

I would like to be able to customise this response so that I can also return some JSON content in the body like:

{
  "Message": "Authorization has been denied for this request."
}

Does anyone know if there is an event I can hook into to customise the response to add this message, so it looks like this?

Base Address:              https://localhost:54701/
Token Expired:             True
IsSuccessStatusCode:       False
Status:                    Unauthorized
StatusCode:                401
WwwAuthenticate:           Bearer error="invalid_token", error_description="The specified 
                           token is invalid.", error_uri="https://documentation.openiddict.com/errors/ID2004"
ReasonPhrase:              Unauthorized
ContentType:               application/json; charset=utf-8
ContentLength:             61
Content:
{
  "Message": "Authorization has been denied for this request."
}

Solution

  • I thought I'd reply here too in case it helps someone who doesn't see the conversation in gitter.

    You do it by intercepting the 401 response in the pipeline with a custom middleware like this: Intercept 401 error in ASP.net Core 2.0 pipeline