Basic Authentication in WordPress

About a month ago, I worked on a plugin to help retrieve a lawyer’s reviews from the AVVO API. One of the key aspects of connecting with the AVVO API was using basic authentication, which was a new method of connecting to an API for me.

What is Basic Authentication?

Basic authentication requires that an authorization header be sent that contains the following:

'Basic ' . base64_encode( "{$username}:{$password}" )

That is the string Basic, followed by a base 64 encoded string comprised of a username, colon, and then password.

Implementing Basic Authentication in WordPress

One of my favorite tools in WordPress is the HTTP API. Not only does it handle different server configurations and simplify the process of making API calls, but it makes setting headers as simple as passing an array of arguments.

Here is an example of how I implemented the basic authentication API call.

function make_basic_auth_request( $api_url, $username, $password ) {
    $request = wp_remote_get(
            'headers' => array(
                'Authorization' => 'Basic ' . base64_encode( "{$username}:{$password}" )

    if ( is_wp_error( $request ) ) {
        return $request;
    } else {
        return json_decode( wp_remove_retrieve_body( $request ) );

The function above will return a WP_Error object if the API call fails or a JSON decoded string if the API call was successful.

A Real Life Example

I have published the WordPress plugin I built to get AVVO reviews on Github.

Note: This plugin only implements the reviews portion of the AVVO API, and its purpose was solely to factor out code from a custom theme. As such, it should not be looked at as complete.

Leave a Reply

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