We are often confused about where to put our authentication code in the Asp.Net life cycle’s pipeline. I believe the below discussion can come to help in that regard.
Modules vs MessageHandler: We can use HTTP message handler to handle our authentication logic. In this case, the message handler examines the HTTP requests and sets the principal. But there are some trade-offs you want to consider before doing that.
- An HTTP module sees all the requests that go through the ASP.NET pipeline, a message handler sees only the requests that are bound to the web API.
- We can set authentication logic for each routes using message handlers
- HTTP modules only work with IIS, so it can only be used for web hosting. Message handler doesn’t depend on IIS. Authentication using message handler can be used for both web hosting and self-hosting.
- HTTP modules are used for IIS logging, auditing etc
- HTTP modules run very early in the ASP.NET pipeline. On the other hand, if the principal is set using the message handler, then it only runs when that message handler runs and the principal’s value gets reset when response leaves the message handler.
Usually, if self-hosting is not needed, HTTP module is the correct place to put authentication code. And if we need self-hosting, we need message handlers to handle authentication logics.