如何为 REST API 统一增加登录验证

追格官方小助手/ 2022年12月12日/ WordPress/ 浏览 926

因为,WordPress 实现的原因,已经无法简单地把 REST API 一禁了之。


如何防止爬虫通过 REST API 爬取文章呢?


给 REST API 加上登录验证就可以了。具体怎么办呢?答案是 rest_authentication_errors 钩子。


add_filter( 'rest_authentication_errors', function( $result ) {
    // If a previous authentication check was applied,
    // pass that result along without modification.
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }

    // No authentication has been performed yet.
    // Return an error if user is not logged in.
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            __( 'You are not currently logged in.' ),
            array( 'status' => 401 )
        );
    }

    // Our custom authentication check should have no effect
    // on logged-in requests
    return $result;
});


返回 true 表示验证通过,false 表示验证失败。返回 WP_Error 表示验证失败的信息。


发表评论

暂无评论,抢个沙发...

客服 工单