Catch ?flush=1 and /dev attempts for non logged in clients

Silverstripe Version: 4.*

Question:
I want to catch and handle the ?flush and /dev/* attempts for non logged in users. I wish to redirect them to home with a flash message “Forbidden action” rather than opening the login form. I tried to catch the call in custom middleware https://docs.silverstripe.org/en/4/developer_guides/controllers/middlewares/
but the login form is invoked before.

class CustomMiddleware implements HTTPMiddleware
{
 // here it's to late
}

How can I catch these requests?

What makes you say it’s too late for that middleware to take effect? You should be able to confirm:

  1. The request was for a /dev/* or flush action
  2. The user was unauthenticated

Then you should be able to output a 403 error or whatever it is you’re doing.

If not logged in I get redirected to login before I can catch it. I don’t want to show the login form. I want to redirect to main page with a flash notice/warning.
I perform logins with cas. For now I set a custom controller on Security/login route…

Right… but the redirection can’t happen until after the response is returned to the user. Which is where your middleware comes in. Middleware is processed on the server-side before returning the response, so the client hasn’t been told to redirect yet.
Your middleware should be able to alter the redirect response so that it redirects to wherever you want to redirect to. If you’re finding your middleware is not being processed in the response which contains the redirect, it is more likely that your configuration needs to be reworked than anything else.