Last active
April 28, 2023 08:33
-
-
Save mattiasghodsian/e01a11c490d32bc095ce858811ff60ea to your computer and use it in GitHub Desktop.
[WordPress] Simple way to protect REST API from the public
This file contains 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
/** | |
* 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