Saturday, July 25, 2020

Extending Apache Authentication To Avoid Repeated Logins

When basic Apache authentication is used to control access to a web site, once authentication is completed, the server includes a session cookie in the HTTP header which is set to expire when the browser is closed.

This is unlike say, Google, where the default is for authentication to persist for a period.

The Apache session token includes the user name and password in clear text and so, while https may be used to protect the credentials in transit, it is clearly not a method which can be recommended for highly secure access.  However, there are definitely use cases where it is suitable (for example to restrict access to content where higher levels of security are not called for and no data updates are being enabled).  On the plus side, Apache authentication is quick and easy to implement.

However, having to re-authenticate each time can be pretty/very/extremely annoying.

This was the case for a custom dictionary site based on the wirdz dictionary engine being developed by JHC Technology Ltd.

The key property of the session cookie is the "expired" field.   Even if this is updated by code, it is reset each time new content is accessed via the http header.  So basically, this can seem a bit like whack-a-mole.

But coming to the rescue is the document unload event which in most cases will have the last work.

Outline code for using this is as follows:

<script>
  window.addEventListener("unload", function(event) {
    var nDays = 14;
    var cookieValue = getCookie("session"); 
    var expires = new Date();
    expires.setTime(+expires + nDays * 24 * 3600 * 1000);
    var options = {expires : expires.toGMTString(), samesite : "Strict"};
    setCookie("session", cookieValue, options);
  });
</script>

This will (hopefully) stop the cookie being deleted for 14 days from the last use and allow the site to be accessed without tiresome logins each.  This code will be needed on each page.

You should note that getCookie and setCookie are NOT standard functions but there are plenty bits of sample code to be found via a quick search engine search.