Protecting PHP Applications with Basic HTTP Authentication on Ubuntu 20.04

HTTP authentication is a mechanism that verifies user credentials to ensure only authorized individuals gain access to specific web resources. To restrict entry to critical endpoints or files in a PHP-based application, one commonly used technique is Basic HTTP Authentication, which mandates that each client request includes a Base64 encoded username and password within the Authorization header.

Note that Base64 is merely used to encode special characters into a web-safe format—it is not a form of encryption. In production environments, credentials must always be transmitted over HTTPS to ensure data security.

This tutorial guides you through setting up a password-protected PHP resource on an Ubuntu 20.04 server. Once authenticated, the endpoint returns product data in JSON format. Invalid or missing login attempts will result in an error response.

Requirements

Ensure you have the following before proceeding:

  • An Ubuntu 20.04 server
  • A user account with sudo privileges
  • A working LAMP stack

Adjust Apache Configuration

Connect to your server via SSH and modify the Apache configuration to permit .htaccess to override main settings, which is essential for enabling HTTP authentication.

Open the main configuration file:

$ sudo nano /etc/apache2/apache2.conf

Locate the following section:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

Change the AllowOverride directive to All like so:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Save your changes and close the editor.

Enable Apache mod_rewrite

Next, activate the mod_rewrite module in Apache, which allows you to process the HTTP_AUTHORIZATION header inside PHP scripts.

$ sudo a2enmod rewrite
$ sudo systemctl restart apache2

Create the Protected PHP Resource

Create a PHP script that displays a list of products in JSON format only for users with valid credentials. Start by opening a new file in the web root directory:

$ sudo nano /var/www/html/sample.php

Insert the following code, substituting EXAMPLE_PASSWORD with a secure password:

<?php

header('Content-Type: application/json');

list($username, $password) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

if ($username != 'john' || $password != 'EXAMPLE_PASSWORD') {
    header("HTTP/1.1 401 Unauthorized");
    $error = [
        'title'      => 'Authentication failed',
        'message'    => 'Invalid username or password',
        'error_code' => '401',
    ];
    echo json_encode($error , JSON_PRETTY_PRINT);
} else {
    $products = [];

    $products[] = [
        'product_id'   => 1,
        'product_name' => 'WIRELESS KEYBOARD',
        'retail_price' => '44.80',
    ];

    $products[] = [
        'product_id'   => 2,
        'product_name' => 'LAPTOP BAG',
        'retail_price' => '28.70',
    ];

    $products[] = [
        'product_id'   => 3,
        'product_name' => 'MOUSE PAD',
        'retail_price' => '5.67',
    ];

    echo json_encode($products, JSON_PRETTY_PRINT);
}

Close and save the file.

Code Breakdown

header(‘Content-Type: application/json’);
Sends a response header so the browser formats the output as JSON.

list($username, $password) = explode(‘:’, base64_decode(…));
Extracts and decodes the Base64 Authorization header into separate variables for the username and password.

Authentication Validation:
The if/else block verifies that the username is john and the password matches EXAMPLE_PASSWORD. If not, it responds with a 401 error and a corresponding JSON message.

Product Listing:
If authentication is successful, the script builds an array of product entries and outputs them as formatted JSON to the client.

 

Final Notes on Security and Functionality

This implementation of HTTP authentication provides a basic yet effective way to secure sensitive resources in a PHP web application. By requiring a username and password, and only allowing access to authorized users, you minimize the risk of exposing valuable data to the public or malicious actors.

It’s critical to remember that Base64 is not a secure method for encryption—it merely encodes the credentials so they can be safely transmitted over HTTP. In any real-world deployment, this authentication mechanism must be paired with HTTPS to prevent credentials from being intercepted in transit.

The server-side verification logic ensures that users submitting incorrect credentials receive a properly formatted 401 Unauthorized error in JSON. Valid users receive structured product data, which could easily be expanded to connect to a database or other backend services for dynamic content delivery.

Configure the .htaccess File for Authentication

To make HTTP authentication function properly, you need to edit the .htaccess file. Open it with the following command:

$ sudo nano /var/www/html/.htaccess

Insert this directive inside the file:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

This rule instructs Apache to assign the content of the $_ENV['HTTP_AUTHORIZATION'] variable to $_SERVER['HTTP_AUTHORIZATION']. That way, the PHP script located at /var/www/html/sample.php can correctly retrieve the encoded user credentials.

Validate HTTP Authentication Functionality

After configuring Apache and securing the PHP resource, it’s time to confirm everything works properly.

Start by making a request without providing any login information. Use the curl command in Linux and pass the -i option to include HTTP headers in the response:

$ curl -i -H 'Accept:application/json' localhost/sample.php

If authentication is not provided, you should receive an output like this:

HTTP/1.1 401 Unauthorized
Date: Tue, 26 Jan 2021 09:27:19 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Length: 121
Content-Type: application/json

{
    "title": "Unauthorized",
    "message": "You are not authorized to access this resource",
    "error_code": "401"
}

Next, retry the request using valid credentials. The -u flag automatically Base64-encodes your username and password before sending:

$ curl -u john:EXAMPLE_PASSWORD -i -H 'Accept:application/json' localhost/sample.php

A successful login will return product data in JSON format, like the following:

HTTP/1.1 200 OK
Date: Tue, 26 Jan 2021 09:30:50 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Length: 331
Content-Type: application/json

[
    {
        "product_id": 1,
        "product_name": "WIRELESS KEYBOARD",
        "retail_price": "44.80"
    },
    {
        "product_id": 2,
        "product_name": "LAPTOP BAG",
        "retail_price": "28.70"
    },
    {
        "product_id": 3,
        "product_name": "MOUSE PAD",
        "retail_price": "5.67"
    }
]

You can also test using incorrect login combinations to ensure they are rejected:

$ curl -u john:WRONG_PASSWORD -i -H 'Accept:application/json' localhost/sample.php
$ curl -u wrong_username:EXAMPLE_PASSWORD -i -H 'Accept:application/json' localhost/sample.php

In both error cases, the response should be similar to this:

HTTP/1.1 401 Unauthorized
Date: Tue, 26 Jan 2021 09:27:19 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Length: 121
Content-Type: application/json

{
    "title": "Unauthorized",
    "message": "You are not authorized to access this resource",
    "error_code": "401"
}

Conclusion

You’ve now implemented HTTP authentication to secure a PHP endpoint on an Ubuntu 20.04 system. This approach ensures only users with valid credentials can retrieve protected data. For an added layer of protection, consider enabling TLS/SSL encryption on your Apache server to secure all transmitted information.

Source: vultr.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

Secure HTTPS Setup on Arch Linux with Apache or Nginx

Security, Tutorial

Linux file permissions with this comprehensive guide. Understand how to utilize chmod and chown commands to assign appropriate access rights, and gain insights into special permission bits like SUID, SGID, and the sticky bit to enhance your system’s security framework.