diff --git a/README.md b/README.md index f97079b..e71cad1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Basic Authentication handler + This plugin adds Basic Authentication to a WordPress site. Note that this plugin requires sending your username and password with every @@ -7,10 +8,12 @@ development and testing. Without SSL we strongly recommend using the [OAuth 1.0a][oauth] authentication handler in production environments. ## Installing + 1. Download the plugin into your plugins directory 2. Enable in the WordPress admin ## Using + This plugin adds support for Basic Authentication, as specified in [RFC2617][]. Most HTTP clients will allow you to use this authentication natively. Some examples are listed below. @@ -35,7 +38,7 @@ $args = array( ```js const WPAPI = require('./wpapi') -const wp = new WPAPI({ +const wp = new WPAPI({ endpoint: 'https://example.com/wp-json', username: 'editor', password: 'password' @@ -43,5 +46,42 @@ const wp = new WPAPI({ ``` [oauth]: https://github.com/WP-API/OAuth1 + [RFC2617]: https://tools.ietf.org/html/rfc2617 + [node-wpapi]: http://wp-api.org/node-wpapi/ + +--- + +## Forcing all API requests to require authorisation + +A few notes on making this work on servers with php-cgi. + +### .htaccess + +If you're using php-cgi you'll need to tweak the .htaccess file slightly. (more info about the issue: https://github.com/LearningLocker/learninglocker/issues/131) + +Change the WordPress block in .htaccess in the root folder to: + +``` +# BEGIN WordPress + +RewriteEngine On +RewriteBase / +RewriteRule ^index\.php$ - [L] +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule . /index.php [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L] + + +# END WordPress +``` + +Then you'll want to stop WordPress from overwriting this if you save permalinks. + +Add this to your functions.php file: (You'll still be able to update your permalinks don't worry...) + +``` +// Stop WordPress from modifying .htaccess permalink rules +add_filter('flush_rewrite_rules_hard','__return_false'); +``` diff --git a/basic-auth.php b/basic-auth.php index 1ef6f85..d7cae36 100644 --- a/basic-auth.php +++ b/basic-auth.php @@ -18,8 +18,20 @@ function json_basic_auth_handler( $user ) { return $user; } + if ( ! isset( $_SERVER['PHP_AUTH_USER'] ) && ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) || isset( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ) ) { + if ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { + $authorization_header = $_SERVER['HTTP_AUTHORIZATION']; + } else { + $authorization_header = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } + + if ( 'Basic ' === substr( $authorization_header, 0, 6 ) ) { + list( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) = explode( ':', base64_decode( substr( $authorization_header, 6 ) ), 2 ); + } + } + // Check that we're trying to authenticate - if ( !isset( $_SERVER['PHP_AUTH_USER'] ) ) { + if ( ! isset( $_SERVER['PHP_AUTH_USER'] ) ) { return $user; }