Like Basic Access Authentication, the Digest scheme is based on a simple challenge-response paradigm. The Digest scheme challenges using a nonce value. A valid response contains a checksum (by default, the MD5 checksum) of the username, the password, the given nonce value, the HTTP method, and the requested URI. In this way, the password is never sent in the clear. Just as with the Basic scheme, the username and password must be prearranged in some fashion.

Introduction

The most commonly utilized regular login authentication system that you will employ on a daily basis while utilizing an online service is password-based login. You need to input a combination of your username/mobile number and a password when using the Password-Based Authentication technique. The individual is authorized only when both of these elements have been verified. However, because today’s customers use multiple online services (apps and websites), it’s tough to keep track of all of their usernames and passwords. As a result of this, end-users engage in unethical behaviors such as forgetting passwords, using the same password for several services, and so on. Cybercriminals enter at this point and begin actions such as phishing, data breaches, and so on. That is the fundamental reason why standard password-based authentication is losing favor and more organizations are turning to advanced additional security authentication factors.

Basic Authentication Scheme

The Basic authentication scheme is based on the model that the client needs to authenticate itself with a user-id and a password for each protection space (realm). The realm value is a free-form string that can only be compared for equality with other realms on that server. The server will service the request only if it can validate the user-id and password for the protection space applying to the requested resource. The Basic authentication scheme utilizes the Authentication Framework as follows.

  1. The scheme name is “Basic”.
  2. The authentication parameter ‘realm’ is REQUIRED.
  3. The authentication parameter ‘charset’ is OPTIONAL. No other authentication parameters are defined,unknown parameters MUST be ignored by recipients, and new parameters can only be defined by revising this specification.

Note that both scheme and parameter names are matched case-insensitively. Upon receipt of a request for a URI within the protection space that lacks credentials, the server can reply with a challenge using the 401 (Unauthorized) status code, and the WWW-Authenticate header field.

For instance:

HTTP/1.1 401 Unauthorized
Date: Mon, 04 Feb 2014 16:50:53 GMT
WWW-Authenticate: Basic realm="NewWorld"

where "NewWorld" is the string assigned by the server to identify the protection space.

A proxy can respond with a similar challenge using the 407 (Proxy Authentication Required) status code and the Proxy-Authenticate header field.

To receive authorization, the client

  1. obtains the user-id and password from the user,
  2. constructs the user-pass by concatenating the user-id, a single colon (“:”) character, and the password,
  3. encodes the user-pass into an octet sequence,
  4. obtains the basic-credentials by encoding this octet sequence using Base64 into a sequence of US-ASCII characters.

The user-id and password MUST NOT contain any control characters. Furthermore, a user-id containing a colon character is invalid, as the first colon in a user-pass string separates user-id and password from one another; text after the first colon is part of the password. User-ids containing colons cannot be encoded in user-pass strings. Note that many user agents produce user-pass strings without checking that user-ids supplied by users do not contain colons; recipients will then treat part of the username input as part of the password. If the user agent wishes to send the user-id “Aladdin” and password “open sesame”, it would use the following header field:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Basic Authentication Flow

The communication between HTTP client and HTTP server in typical Basic authentication . The flow usually looks like this.

  1. A client requests a page that requires authentication. But usually we don’t send username and password here. This is because the client does not know whether the page requires authentication or not.
  2. The server returns a 401 response code and informs the client about the authentication realm and authentication method (basic authentication).
  3. The client then presents the user with an authentication realm (usually a brief description of the computer or system being accessed) and prompts for a username and password. The user can also cancel here.
  4. After the user enters a username and password, the client adds an authorization header to the request and resends it.
  5. If authentication is successful, the server will process requests for pages that require authentication. On the other hand, if the username or password is incorrect, the server will return a 401 response code again. The client then again prompts the user for a username and password.

PHP Example Code

<?php
    $realm = 'Restricted area';

    //user => password
    $users = array('admin' => 'mypass', 'guest' => 'guest');


    if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
        header('HTTP/1.1 401 Unauthorized');
        header('WWW-Authenticate: Digest realm="'.$realm.
            '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

        die('Text to send if user hits Cancel button');
    }


    // analyze the PHP_AUTH_DIGEST variable
    if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
        !isset($users[$data['username']]))
        die('Wrong Credentials!');


    // generate the valid response
    $A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
    $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
    $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

    if ($data['response'] != $valid_response)
        die('Wrong Credentials!');

    // ok, valid username & password
    echo 'You are logged in as: ' . $data['username'];


    // function to parse the http auth header
    function http_digest_parse($txt)
    {
        // protect against missing data
        $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
        $data = array();
        $keys = implode('|', array_keys($needed_parts));

        preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

        foreach ($matches as $m) {
            $data[$m[1]] = $m[3] ? $m[3] : $m[4];
            unset($needed_parts[$m[1]]);
        }

        return $needed_parts ? false : $data;
    }
?>
  1. Request without authentication :

     Request URL: http://localhost/auth/index.php
     Request Method: GET
     Status Code: 401 Unauthorized
     Remote Address: [::1]:80
     Referrer Policy: strict-origin-when-cross-origin
    
  2. Server response indicating that authentication is required :

     Connection: Keep-Alive
     Content-Length: 39
     Content-Type: text/html; charset=UTF-8
     Date: Mon, 05 Sep 2022 14:05:24 GMT
     Keep-Alive: timeout=5, max=100
     Server: Apache/2.4.48 (Win64) OpenSSL/1.1.1l PHP/7.4.23
     WWW-Authenticate: Basic realm="MyRealm"
     X-Powered-By: PHP/7.4.23
    

    basic_auth

  3. Presented by client and entered by user.
  4. Request with authentication (username “root”, password “password”): basic_auth

     Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
     Accept-Encoding: gzip, deflate, br
     Accept-Language: en-US,en;q=0.9,ja;q=0.8,zh-CN;q=0.7,zh;q=0.6
     Authorization: Basic YWRtaW46ZGFtaW4=
     Cache-Control: no-cache
     Connection: keep-alive
     Host: localhost
     Pragma: no-cache
     sec-ch-ua: "Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"
     sec-ch-ua-mobile: ?0
     sec-ch-ua-platform: "Windows"
     Sec-Fetch-Dest: document
     Sec-Fetch-Mode: navigate
     Sec-Fetch-Site: none
     Sec-Fetch-User: ?1
     Upgrade-Insecure-Requests: 1
     User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
    
  5. Server response

     HTTP / 1.1  200  OK 
     Connection: Keep-Alive
     Content-Length: 61
     Content-Type: text/html; charset=UTF-8
     Date: Mon, 05 Sep 2022 14:13:10 GMT
     Keep-Alive: timeout=5, max=100
     Server: Apache/2.4.48 (Win64) OpenSSL/1.1.1l PHP/7.4.23
     X-Powered-By: PHP/7.4.23
    

    image info

Security Considerations

The Basic authentication scheme is not a secure method of user authentication, nor does it in any way protect the entity, which is transmitted in cleartext across the physical network used as the carrier. HTTP does not prevent the addition of enhancements (such as schemes to use one-time passwords) to Basic authentication. The most serious flaw of Basic authentication is that it results in the cleartext transmission of the user’s password over the physical network. Many other authentication schemes address this problem. Because Basic authentication involves the cleartext transmission of passwords, it SHOULD NOT be used (without enhancements such as HTTPS) to protect sensitive or valuable information. A common use of Basic authentication is for identification purposes requiring the user to provide a user-id and password as a means of identification, for example, for purposes of gathering accurate usage statistics on a server. When used in this way it is tempting to think that there is no danger in its use if illicit access to the protected documents is not a major concern. This is only correct if the server issues both user-id and password to the users and, in particular, does not allow the user to choose his or her own password. The danger arises because naive users frequently reuse a single password to avoid the task of maintaining multiple passwords. If a server permits users to select their own passwords, then the threat is not only unauthorized access to documents on the server but also unauthorized access to any other resources on other systems that the user protects with the same password. Furthermore, in the server’s password database, many of the passwords may also be users’ passwords for other sites. The owner or administrator of such a system could therefore expose all users of the system to the risk of unauthorized access to all those other sites if this information is not maintained in a secure fashion. This raises both security and privacy concerns. If the same user-id and password combination is in use to access other accounts, such as an email or health portal account, personal information could be exposed.

Basic authentication is also vulnerable to spoofing by counterfeit servers. If a user can be led to believe that she is connecting to a host containing information protected by Basic authentication when, in fact, she is connecting to a hostile server or gateway, then the attacker can request a password, store it for later use, and feign an error. Server implementers ought to guard against this sort of counterfeiting; in particular, software components that can take over control over the message framing on an existing connection need to be used carefully or not at all.

Servers and proxies implementing Basic authentication need to store user passwords in some form in order to authenticate a request. These passwords ought to be stored in such a way that a leak of the password data doesn’t make them trivially recoverable. This is especially important when users are allowed to set their own passwords, since users are known to choose weak passwords and to reuse them across authentication realms. While a full discussion of good password hashing techniques is beyond the scope of this document, server operators ought to make an effort to minimize risks to their users in the event of a password data leak. For example, servers ought to avoid storing user passwords in plaintext or as unsalted digests. For more discussion about modern password hashing techniques.