How to exclude Request URIs from Basic Auth in apache2 | Ubuntu

I had setup Basic Auth for an Opencart project for browser authentication to allow access to only relevant users in UBUNTU. The project had rest API for mobile. When I had to call an endpoint from the rest API to get some details from Opencart Project it requires an access_token to be generated from API and by using that access_token with every request I could get details from the API.

The problem was Basic Auth that I had setup for project and because of that I cannot access API as I can only use 1 method to access the API that is GET method to get the details from opencart, I cannot use 2 methods i.e. Auth Header and GET methods. So, what I am trying to do is to simply disable Basic Auth if the Request_URI includes rest api calls.

Everywhere I found the solution like to add the following in vhost of project:

<Directory /var/www/html/projectexample>
 AllowOverride All        
 # Auth stuff
 AuthName "Authentication Required"
 AuthType Basic
 AuthUserFile /etc/apache2/.htpasswd
 Order allow,deny
 Deny from all
 Satisfy any
 <RequireAny>
    <RequireAll>
        Require expr %{REQUEST_URI} =~ m#^/api/rest/.*#
    </RequireAll>
    Require valid-user
 </RequireAny>
</Directory>

This should have been worked, right? but it didn't because I had SEO URLs enabled in my project.

I had also tried to use apache2 SetEnvIf environment variable like following but it didn't workout either:

<Directory /var/www/html/projectexample>
  AllowOverride All        
  # Auth stuff
  AuthName "Authentication Required"
  AuthType Basic
  AuthUserFile /etc/apache2/.htpasswd
  SetEnvIf Request_URI "^/api/*" allow=1
  #SetEnvIf Request_URI "^/(api/*)" allow=1
  Order allow,deny
  Require valid-user
  Allow from env=allow
  Deny from env!=allow
  Satisfy any
</Directory>

The Solution which worked out for SEO URLs is the following:

<Directory /var/www/html/projectexample>
        AllowOverride All
    </Directory>
<Location "/">
  # Default to Basic Auth protection for any stie
     AuthType Basic
     AuthName "Authentication required"
     AuthUserFile /etc/apache2/.htpasswd
     Require valid-user
     # If the request goes to a rest page: bypass basic auth
     SetEnvIf Request_URI ^/api/ noauth=1
     Allow from env=REDIRECT_noauth
     Allow from env=noauth
     Order allow,deny
     Satisfy any
     Deny from env!=noauth
</Location>

Allow from env=REDIRECT_noauth is doing the trick here for SEO URLs.

I hope it may help someone!

 

Haroon Ejaz

A Software Engineer, primarily focusing on PHP development with over 3 years experience and a Bachelors degree in Information Technology.