我正在实施REST API 具有fetch() 作为请求的承诺Password protected 带有的页面custom table 不使用插件(仅使用WP REST API 这已经被合并到WordPress核心-向WordPress团队竖起大拇指,这是一个明智的举动,谢谢)。
一切都很好,只是我不能Authorization 在HTTP请求的标头中工作(始终传递,即使没有JWT或false标记,请参阅最后一步6.) 最后)。
以下是我的步骤:
1.)在MySQL中创建自定义表
使用自定义表安装WordPress上的MySQL数据库your_custom_table
, 4列(id
, column_1
, column_2
, timestamp
) 和6个首字母记录。2.)创建受密码保护的页面
一
<script> ... </script>
):<form id="form1" name="form1">
<button id="get" onclick="getValues()">GET</button>
<button id="insert" onclick="insertValues()">CREATE</button>
<button id="update" onclick="updateValues()">UPDATE</button>
</form>
<script>
let yourData = [];
let yourDataNew = {};
let yourDataUpdated = {};
let token = "";
function getValues() {
event.preventDefault();
//READ data
getYourData();
};
function insertValues() {
event.preventDefault();
//CREATE new datarecord
yourDataNew = {"column_1": "test-1", "column_2": "test-2"};
insertYourData(yourDataNew);
};
function updateValues() {
event.preventDefault();
//UPDATE datarecord
let idOfLastRecord = yourData[yourData.length-1].id;
yourDataUpdated = {"id": idOfLastRecord, "column_1": "test-1-modified", "column_2": "test-2-modified"};
updateYourData(yourDataUpdated);
};
//GET value of Access Cookie wp-postpass_{hash}
token = ("; "+document.cookie).split("; wp-postpass_675xxxxxx =").pop().split(";").shift();
//token = \'24P%24BhPU2oE3ux8v4FFfSFbB9onTPNnglM.\'
console.log(\'TOKEN: \' + token);
// Here comes the REST API part:
// HTTP requests with fetch() promises
function getYourData() {
let url = \'https://oilamerica.com.pa/wp-json/wp/v2/your_private_page/data\';
fetch(url, {
method: \'GET\',
credentials: \'same-origin\',
headers:{
\'Content-Type\': \'application/json\',
//credentials: \'same-origin\', <-- no authorization needed
\'Accept\': \'application/json\',
//\'Authorization\': \'Bearer \' + token <-- no authorization needed
}
}).then(res => res.json())
.then(response => get_success(response))
.catch(error => failure(error));
};
function insertYourData(data) {
let url = \'https://oilamerica.com.pa/wp-json/wp/v2/your_private_page/data\';
fetch(url, {
method: \'POST\',
credentials: \'same-origin\',
headers:{
\'Content-Type\': \'application/json\',
\'Accept\': \'application/json\',
\'Authorization\': \'Bearer \' + token
},
body: JSON.stringify(data)
}).then(res => res.json())
.then(response => create_success(response))
.catch(error => failure(error));
};
function updateYourData(data) {
let url = \'https://oilamerica.com.pa/wp-json/wp/v2/your_private_page/data\';
fetch(url, {
method: \'PUT\',
credentials: \'same-origin\',
headers:{
\'Content-Type\': \'application/json\',
\'Accept\': \'application/json\',
\'Authorization\': \'Bearer \' + token
},
body: JSON.stringify(data)
}).then(res => res.json())
.then(response => update_success(response))
.catch(error => failure(error));
};
// fetch() promises success functions:
function get_success(json) {
data = JSON.stringify(json);
yourData = JSON.parse(data);
console.log(\'GET\');
console.log(yourData);
};
function create_success(json) {
let insertResponse = JSON.stringify(json);
insertResponse = JSON.parse(insertResponse);
console.log(\'CREATE\');
console.log(insertResponse);
};
function update_success(json) {
let updateResponse = JSON.stringify(json);
updateResponse = JSON.parse(updateResponse);
console.log(\'UPDATE\');
console.log(updateResponse);
};
function failure(error) {
console.log("Error: " + error);
};
</script>
添加后Password Protected 第“”页您的私人页面;我得到以下结果:使用密码登录的结果页面。请注意,页面显示在页面的小部件中,即使您的菜单中没有包含页面,而在;“私人”;对于未经授权的访问者,该页面不可见。
3.)已编辑的函数。我安装的主题的php
Code (添加了我的PHP 代码输入function.php
我安装的主题的)/**
* Add here your custom CRUD functions
*/
function get_your_data($request) {
global $wpdb;
$yourdata = $wpdb->get_results("SELECT * FROM your_custom_table");
return rest_ensure_response( $yourdata );
};
function insert_your_data($request) {
global $wpdb;
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : \'\';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$newrecord = $wpdb->insert( \'your_custom_table\', array( \'column_1\' => $decoded[\'column_1\'], \'column_2\' => $decoded[\'column_2\']));
};
if($newrecord){
return rest_ensure_response($newrecord);
}else{
//something gone wrong
return rest_ensure_response(\'failed\');
};
header("Content-Type: application/json; charset=UTF-8");
};
function update_your_data() {
global $wpdb;
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : \'\';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$updatedrecord = $wpdb->update( \'your_custom_table\', array( \'column_1\' => $decoded[\'column_1\'], \'column_2\' => $decoded[\'column_2\']), array(\'id\' => $decoded[\'id\']), array( \'%s\' ));
};
if($updatedrecord){
return rest_ensure_response($updatedrecord);
}else{
//something gone wrong
return rest_ensure_response(\'failed\');
};
header("Content-Type: application/json; charset=UTF-8");
};
add_action(\'rest_api_init\', function() {
/**
* Register here your custom routes for your CRUD functions here
*/
register_rest_route( \'wp/v2/your_private_page\', \'/data\', array(
array(
\'methods\' => \'GET\',
\'callback\' => \'get_your_data\'
),
array(
\'methods\' => \'POST\',
\'callback\' => \'insert_your_data\'
),
array(
\'methods\' => \'PUT\',
\'callback\' => \'update_your_data\'
),
));
});
4。)测试Cookie值检索部分(JWT令牌)
正在检索cookiewp_postpass_ 675xxxxx值(即JWT token) 而且做得很好5.)测试CRUD函数(GET、POST和PUT)
GET: 工作正常(未经授权,因为在我们的前端读取数据是公开的)
新记录为inserted 正确设置到我的自定义表:
PUT: 工作良好(经授权,即受保护)
上次记录已updated 在我的自定义表中正确
6。)在没有令牌的情况下测试我的CRUD函数unauthorized 访问方式:
- Eliminating 手动令牌过帐false token 在HTTP标头中
\'Authorization\': \'Bearer \' + false-token
execute 我的内联<script> ... </script>
从另一个具有no password protectionBIG SURPRISE :
也就是说,\'Authorization\': \'Bearer \' + token
did not force 自动地Authorization 为了prevent unauthorized access 到我的REST API。
因此,现在我的问题来了:
我怎样才能force Authorization 我对REST API的请求,以便unauthorized visitors cannot modify 我们的数据(“POST”和“PUT”)?欢迎提出任何意见和建议。
非常感谢。