Search code examples
apachemod-auth-form

httpd/mod_auth_form How to display an error message on invalid credentials?


Using inline form with ErrorDocument 401, how can I get an error message to be displayed when the user fails to login?

Expected features are to still work (e.g. login redirect). No login/logout URLs seen in user's browser. When the user logs out, the message should not be shown when they are 401'd back to the inline login page.

I am currently using an onsubmit function to set a flag in sessionStorage. If the page loads (body onload function) and sees this flag, it will show the error message (e.g. user entered wrong credentials and are back here again). This works fine, until they logout. They are 401'd to the login page and the flag is still there, so they see the error message.

I need to clear the message somehow.

Well, GET vs POST! The initial page load is a GET and the logout is a GET; so, only failed logins would be loading this page with a POST.

Let's activate SSI and use an env var (this is on both login and logout Location directives):

SetEnvIf Request_Method "^GET$" LOGIN-ERROR-CLEAR="1"

Inject some JS to our init to clear the sessionStorage:

<!--#if expr="reqenv('LOGIN-ERROR-CLEAR') == '1'" -->
sessionStorage.removeItem('login-attempted');
<!--#endif -->

Sounds logical...but, it doesn't work. The JS is not injected.

  • GET /logout -> 307 to "/" (due to AuthFormLogoutLocation "/")
  • GET / -> 401 with content of /login.html
  • error message is wrongly shown

All GETs, yet the JS was not injected. What is going on? I am back where I started before using SetEnvIf - there is no difference. It's not doing anything!

Is there a better way to trigger an error message and clear the trigger after successful login or logout? This shouldn't be this hard!


Solution

  • Found out I could use the variables directly in the SSI; so, I removed the SetEnvIfs from my vhost. Also, REQUEST_METHOD is the wrong one to use. REDIRECT_REQUEST_METHOD is the one to look for. In the end, this seems to be working:

    <!--#comment This block uses SSI/mod_include. -->
    <!--#if expr='v("REDIRECT_REQUEST_METHOD") == "GET"' -->
    sessionStorage.removeItem('login-attempted');
    <!--#endif -->