Improved security exception handling in middleware.