I'm looking for away to eliminate the intrusive instant prompt for credentials when basic authentication is used and instead serve a nice page that tells the user where he is and what credentials to use if he wants to proceed.

I came up with this simple .htaccess:

# .htaccess in /auth/ of DocumentRoot
AuthType Basic
AuthName "Protected Area"
AuthUserFile /path/to/htdocs/auth/.htpasswd    
    # Grant access to unauthenticated users via GET
    # Warning!!! Make sure redirect to "logininfo.html" works!!!
    Require expr "%{HTTP:Authorization} == ''"
    Require method GET HEAD OPTIONS
Require expr "%{REQUEST_URI} == '/auth/loginfail.html'"
Require valid-user 

ErrorDocument 401 /auth/loginfail.html

RewriteEngine On
# show unauthenticated users a nice login info page
RewriteCond expr "%{HTTP:Authorization} == ''"
RewriteRule .* logininfo.html

It grants access without authentication when HTTP Authorization header is empty for GET/HEAD/OPTIONS requests. All unauthenticated requests are handled by logininfo.html POST requests (e.g. Login Button) require authentication, thus trigger the credentials prompt.

It works, but I think it is kind of risky and counter intuitive to generally grant access for users that don't authenticate. But I think it is okay in this case. Is there a security risk with this solution I've overseen?

I would also be interested in a solution for serving my logininfo.html with HTTP 401/403 instead of 200. Thanks.

  • 2
    I will add my personal opinion. Users guessing a password is not a concern using basic auth, it becomes a problem when they are guessing 10's to 100's a second to brute force their way in, which can be prevented by using fail2ban and temporary block users for X attempts, but... sites with security in mind will never use the basic authentication system provided by Apache, it was never designed for handling lots of multiple users nor is it scalable. It is always best to secure access at the app level. Generally, it is prefered to use Service Side Scripting, PHP, ASP, Python, Java or Ruby etc. – Simon Hayter Feb 24 '18 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.