Created
March 17, 2021 09:51
-
-
Save daffodilistic/fdf3b58e5a08e118e12621c212d1c809 to your computer and use it in GitHub Desktop.
Basic plugin to demonstrate enabling application passwords and REST endpoint security via HTTP Basic auth
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: Application Password and REST Authentication Test Plugin | |
* Description: Basic plugin to demonstrate enabling application passwords and REST endpoint security via HTTP Basic auth | |
* Version: 0.1.0 | |
* Requires at least: 5.6 | |
* Author URI: https://github.com/daffodilistic/ | |
* Author: Soh Thiam Hing | |
* License: The Unlicense | |
* License URI: https://spdx.org/licenses/Unlicense.html | |
*/ | |
namespace Daffodilistic; | |
use \WP_Error; | |
use \WP_REST_Request; | |
use \WP_REST_Response; | |
// Force app passwords to be available | |
add_filter('wp_is_application_passwords_available', '__return_true'); | |
add_action('rest_api_init', function () { | |
register_rest_route('daffodilistic/app_passwd_auth', 'set_auth_cookie', array( | |
'methods' => 'GET', | |
'callback' => __NAMESPACE__ . '\\set_auth_cookie', | |
'permission_callback' => __NAMESPACE__ . '\\validate_app_password' | |
)); | |
}); | |
function validate_app_password(WP_REST_Request $request) | |
{ | |
return wp_validate_application_password(null); | |
} | |
function set_auth_cookie(WP_REST_Request $request) | |
{ | |
$user_id = $request->get_param("user_id") ?? null; | |
if ($user_id == null) { | |
return new WP_Error('404', 'User does not exist'); | |
} | |
wp_set_auth_cookie($user_id); | |
return "OK"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment