Instantly share code, notes, and snippets.

Embed
What would you like to do?
Filter WP Basic HTTP Authentication Credentials
<?php
/**
* Plugin Name: Filter WP Basic HTTP Authentication Credentials
* Description: Filter WP Basic HTTP Authentication Credentials to use environment variables
* Author: James Morrison
* Version: 1.0.0
* Author URI: https://www.jamesmorrison.me
**/
// Filter the credentials
add_filter( 'wp_basic_auth_credentials',
function( $credentials ) {
// Ensure the expected server variable is available
if ( ! isset( $_SERVER['http_authentication_credentials'] ) ) {
return $credentials;
}
// $credentials should be an array, just in case it isn't, validate and create one if need be
if ( ! is_array( $credentials ) ) {
$credentials = [];
}
// Remove the example user
// This is a key => value based array so we can simply unset the array key
unset( $credentials['example_user'] );
// Load credentials from the environment variable
// Expected format is:
// user_1:password_1,user_2:password_2
$environment_credentials = sanitize_text_field( $_SERVER['http_authentication_credentials'] );
// Break the string to an array of individual sets of usernames and passwords
$credentials_array = explode( ',', $environment_credentials );
// Loop through each set of credentials
foreach ( $credentials_array as $username_password ) {
// Break the user_1:password_1 to an array
$username_password_array = explode( ':', $username_password );
// Add the username and password to the $credentials array
$credentials[ $username_password_array[0] ] = $username_password_array[1];
}
// Send back our credentials
return $credentials;
}, 1, 1
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment