Last active
January 5, 2018 20:12
-
-
Save jamesmorrison/2d9f35f00a7fd778bc79cbe304b7f683 to your computer and use it in GitHub Desktop.
Filter WP Basic HTTP Authentication Credentials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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