Just thinking off the top of my head here.
Could you use an “if” statement to check for the response and respond accordingly?
If it is a 401, you could display the authentication page inside of an iFrame, or present a link that says “click here to authenticate” and set the link’s URL to the appropriate page.
I might be misunderstanding something but that is what comes to my mind at the moment.