2016-08-17 30 views
1

我使用WP REST API和oAuth1.0服務器插件進行身份驗證。到目前爲止,郵差需要被認證才能訪問端點,但瀏覽器不需要認證。任何人都可以通過瀏覽器訪問API響應。是否可以限制瀏覽器中的API訪問?我不想讓未經認證的人查看API的敏感數據。WordPress REST API - 瀏覽器無需身份驗證即可提供JSON響應

P.S. oAuth1.0服務器插件已激活,Postman中的身份驗證完美無缺!

例子。當我在瀏覽器中輸入http://localhost:8080/api/v1/categories我得到類別的JSON響應,當我在郵差進入端點一樣,我得到:

{ 
    "code": "json_oauth1_missing_parameter", 
    "message": "Missing OAuth parameter oauth_token", 
    "data": { 
    "status": 401 
    } 
} 

回答

0

好了,搜索了一整天,我終於來到了兩種可能的解決方案之後。兩人對我都很好(親自選擇了第一個)。

add_filter('rest_pre_dispatch', function($result){ 
    if (is_user_logged_in()) { 
     return $result; 
    } else { 
     return new WP_Error('rest_requires_authentication', __('Authentication is required for this action.'), array('status' => 403)); 
    } 
}); 

或者

add_filter('rest_authentication_errors', function($result) { 
    if (!empty($result)) { 
     return $result; 
    } 
    if (!is_user_logged_in()) { 
     return new WP_Error('restx_logged_out', 'Sorry, you must be logged in to make a request.', array('status' => 401)); 
    } 
    return $result; 
}); 

可悲的是,WP REST API插件不處理這本身。