Basic Authentication In A Rest API

One of the methods to authenticate with a REST API is by Basic Authorization. Basic uses two pieces of information known to the user, a Username and a Password. I’ll show you how to write the code.

The first thing to do is to send out a conditional statement on the REST API authentication page that says if the authentication method has not been sent, then exit with a 401 unauthorized header. We can achieve this goal by making sure PHP_AUTH_USER is set like this.

    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header("WWW-Authenticate: Basic realm=\"Private Area\"");
        header("HTTP/1.0 401 Unauthorized");
        print "Sorry - you need to enter a username and password\n";
        exit;
    }

If the user does not enter in a username and password, then the page will send out a 401 unauthorized response and exit. Using Postman to test this response, we get the expected header.

To receive a username and password, we need to add a conditional statement saying that – if the username is bill for example and the password is 1234, then grant access to the authorized area. This snippet shows how to do that.

	if (!isset($_SERVER['PHP_AUTH_USER'])) {
	    header("WWW-Authenticate: Basic realm=\"Private Area\"");
	    header("HTTP/1.0 401 Unauthorized");
	    print "Sorry - you need to enter a username and password\n";
		exit;
	} else {
		if (($_SERVER['PHP_AUTH_USER'] === 'bill' && ($_SERVER['PHP_AUTH_PW'] === '1234'))) {
			print "You are in the private area";
		} else {
		header ("WWW-Authenticate: Basic realm=\"Private Area\"");
		header ("HTTP/1.0 401 Unauthorized");
		print "Sorry, you need proper credentials";
		}
	}

So, let’s test this new code in Postman to see how it works. First, go to the Authorization section of Postman and select Basic Authorization from the dropdown menu.

SELECT BASIC AUTHORIZATION

Here is the response when the correct username and password have been entered.

Just a side note: This example only shows the concept, and does not dive into a dynamic site using a relational database. A database is one method to retrieve the stored usernames and passwords to compare them to what the user entered. Of course storing confidential information directly is not advisable and therefore if you are doing this you should store hashed or encrypted values or only. To compare the un-hashed values that the user entered, you will need to hash those entries using the same method as the stored hashed values. Be careful when selecting a hashing function. You need to use a modern approach that protects against timing attacks and insecure hashing algorithms. See the PHP manual for more information.

Leave a Reply

Your email address will not be published. Required fields are marked *