One of my ASP.NET Core applications hosts both an API and a website. There are multiple places where authentication and authorizaton rules are checked:
- In the
Accountcontroller
Login
Action method - In a custom
AuthorizationHandler
- In a custom
IAuthorizationFilter
Remark: Don’t ask me why we have all these places, that is maybe something for another blog post.
Recently I had to make a change to the application so that depending if the request was coming from the website or through the API, a different message was returned when authorization failed. I didn’t like the idea that I had to implement the same change 3 times, so I started to search for a better solution…
The solution
I found the solution in the implementation of the IAuthorizationMiddlewareResultHandler. By implementing this middleware, you can:
- Return customized responses.
- Enhance the default challenge or forbid responses.
That is exactly what we need!. Here is a simplified example:
Register this middleware in your ASP.NET Core Program.cs
file: