Skip to content

Instantly share code, notes, and snippets.

@railmedia
Last active December 6, 2023 14:27
Show Gist options
  • Save railmedia/0e76c0e988c03d06dff0002875bfc5b9 to your computer and use it in GitHub Desktop.
Save railmedia/0e76c0e988c03d06dff0002875bfc5b9 to your computer and use it in GitHub Desktop.
WordPress REST user Basic auth example
//Send request to http(s)://yourdomain.com/wp-json/test/v1/test
class WP_REST {
function __construct() {
add_action( 'rest_api_init', array( $this, 'routes' ) );
}
function auth_user( $request ) {
$valid = false;
$headers = $request->get_headers();
if( isset( $headers['authorization'] ) && isset( $headers['authorization'][0] ) ) {
$auth = str_replace('Basic ', '', $headers['authorization'][0]);
$auth = base64_decode( $auth );
$auth = explode( ':', $auth );
$user = isset( $auth[0] ) && isset( $auth[1] ) ? wp_authenticate( $auth[0], $auth[1] ) : null;
if( ! is_wp_error( $user ) && isset( $user->caps['administrator'] ) ) {
$valid = true;
}
}
return $valid;
}
function routes() {
$namespace = 'test/v1';
register_rest_route( $namespace, '/test', array( // This one needs to be in the plugin
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'callback' ),
'permission_callback' => function ( $request ) {
return $this->auth_user( $request );
},
'args' => array()
) );
}
function callback( $request ) {
return new \WP_REST_Response( array(
), 200 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment