Skip to content

Instantly share code, notes, and snippets.

@mattiasghodsian
Last active April 28, 2023 08:33
Show Gist options
  • Save mattiasghodsian/e01a11c490d32bc095ce858811ff60ea to your computer and use it in GitHub Desktop.
Save mattiasghodsian/e01a11c490d32bc095ce858811ff60ea to your computer and use it in GitHub Desktop.
[WordPress] Simple way to protect REST API from the public
/**
* Author: Mattias Ghodsian
* Donate a cup of coffee: https://www.buymeacoffee.com/mattiasghodsian
* Donate Eth: 0xBBB96204E45D11C9799c6B12E6eE6F0d4A071Ef5
*
* custom_rest_api_authentication_token
*
* Protect REST API from the public | Generate token: https://bit.ly/2W5qDrB
*
* @param obj $wp_rest_server
* @return json
*/
add_filter( 'rest_api_init', 'custom_rest_api_authentication_token', 99 );
function custom_rest_api_authentication_token($wp_rest_server){
if ( !isset( $_REQUEST['token'] ) ) {
return wp_send_json( ['code' => '401', 'message' => 'authentication token missing'] , 401);
exit();
}
if ( $_REQUEST['token'] !== "token here") {
return wp_send_json( ['code' => '403', 'message' => 'authentication token invalid'] , 403);
exit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment