WordPress WP REST API按域限制请求 [英] WordPress WP REST API limiting requests by domain

查看:105
本文介绍了WordPress WP REST API按域限制请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎会更加明显.我使用WordPress管理外部网站的内容. WordPress内容是通过WP REST API显示的,而我使用ajax和JS将内容显示到此远程站点. (例如 https://example.com//wp-json/wp/v2/pages/23 ).一切都基于SSL,并且一切正常.我如何简单地做到这一点,以便仅从某个域(远程站点)允许此ajax GET请求? WP API仅用于显示数据.

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.

推荐答案

我只是看过php服务器变量并弄清楚了. $ _SERVER ['HTTP_ORIGIN'];是我抢到的那个.就像魅力一样!

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;

}

这篇关于WordPress WP REST API按域限制请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆