【问题标题】:WordPress: Get posts from other site with BasicAuth protection via Rest APIWordPress:通过 Rest API 从具有 BasicAuth 保护的其他站点获取帖子
【发布时间】:2022-01-21 13:27:36
【问题描述】:

我想从一个有 BasicAuth 保护的网站上发帖。

要从网站获取帖子,我使用以下代码 (from here):

// Disable direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Get posts via REST API.
 */
function get_posts_via_rest() {

    // Initialize variable.
    $allposts = '';
    
    // Enter the name of your blog here followed by /wp-json/wp/v2/posts and add filters like this one that limits the result to 2 posts.
    $response = wp_remote_get( 'https://www.sumydesigns.com/wp-json/wp/v2/posts?per_page=2' );

    // Exit if error.
    if ( is_wp_error( $response ) ) {
        return;
    }

    // Get the body.
    $posts = json_decode( wp_remote_retrieve_body( $response ) );

    // Exit if nothing is returned.
    if ( empty( $posts ) ) {
        return;
    }

    // If there are posts.
    if ( ! empty( $posts ) ) {

        // For each post.
        foreach ( $posts as $post ) {

            // Use print_r($post); to get the details of the post and all available fields
            // Format the date.
            $fordate = date( 'n/j/Y', strtotime( $post->modified ) );

            // Show a linked title and post date.
            $allposts .= '<a href="' . esc_url( $post->link ) . '" target=\"_blank\">' . esc_html( $post->title->rendered ) . '</a>  ' . esc_html( $fordate ) . '<br />';
        }
        
        return $allposts;
    }

}

它有效。 但是我想从中获取帖子的网站使用 BasicAuth 保护。 所以没有结果。

我了解到 Rest API 无法处理 BasicAuth。 而且我必须使用像Basic Authentication handler这样的插件

但我不确定如何使用它。 有没有办法把它集成到代码中?

【问题讨论】:

    标签: php json wordpress wordpress-rest-api wp-api


    【解决方案1】:

    在 WordPress 中 WP_Http 是通过 wp_remote_get() 函数生成的。

    使用 GET 方法执行 HTTP 请求并返回其响应。

    简而言之,wp_remote_get() 充当WP_Http 的包装器。

    使用 GET 方法执行 HTTP 请求并返回其响应。

    根据 BasicAuth 文档:

    <?php
    
    $args = array(
        'headers' => array(
            //here the credentials are referring to a wordpress account on the targeted website
            'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
        ),
    );
    
    wp_remote_get('https://...com/wp-json/wp/v2/posts', $args);
    //...
    

    您绝对可以阻止 api 访问(但本机并非如此)。

    请记住,使用 BasicAuth 可能没有用处。当人们为保护 api 而烦恼时,通常需要管理员访问级别才能访问 api。

    另一种方法是使用像 puppeteer 这样的抓取工具从头开始重新创建 api 并将其托管在单独的服务器上。 (听起来很复杂,其实很简单)

    【讨论】:

    • 再一次默认情况下,任何 WordPress 网站都有一个开放的 api。如果有人对 api 访问添加限制,大多数情况下需要管理员登录。你可能没有。
    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 2019-10-25
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    相关资源
    最近更新 更多