WordPress WP REST API limiting requests by domain

谁说胖子不能爱 提交于 2019-12-11 01:39:44

问题


This seems like it would be more obvious. I use WordPress to manage content for an external site. The WordPress content is displayed via the WP REST API and I display content with ajax and JS to this remote site. (e.g. https://example.com//wp-json/wp/v2/pages/23). Everything is on SSL and it all works great. How can I simply make it so this ajax GET request is only allowed from a certain domain - the remote site? The WP API is only used to display data.


回答1:


I just had look at the php server variables and figure this out. $_SERVER['HTTP_ORIGIN']; was the one that I grab. Works like a charm!

add_filter( 'rest_authentication_errors', 'gc_filter_incoming_connections' );

function gc_filter_incoming_connections( $errors ){

    $allowed_origins = array('https://www.example.com'); // url that you want to access your WP REST API
    $request_origin = $_SERVER['HTTP_ORIGIN'];

    if( ! in_array( $request_origin, $allowed_origins ) )
        return new WP_Error( 'forbidden_access', 'Access denied', array( 'status' => 403 ) );

    return $errors;

}


来源:https://stackoverflow.com/questions/43923877/wordpress-wp-rest-api-limiting-requests-by-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!