首页 文章

WordPress和JWT与自定义API休息 endpoints

提问于
浏览
2

我需要为WordPress提供一个插件,它将有很少的自定义API endpoints ,我已经安装了这两个插件

我创建了自定义 endpoints :

add_action('rest_api_init', function ($data) {
    register_rest_route('mladi-info/v1', '/user/favorites', [
        'methods' => 'GET',
        'callback' => 'mi_get_favorite_posts'
    ]);
});

我需要保护此 endpoints ,以便只处理那些发送了JWT令牌的请求(使用/ wp-json / jwt-auth / v1 / token endpoints 发送用户名和密码生成),否则它应返回401状态码 . 我怎么做?

1 回答

  • 2

    您应该在注册新路由时添加permission_callback参数 .

    add_action('rest_api_init', function ($data) {
            register_rest_route('mladi-info/v1', '/user/favorites', 
                array(
                    'methods' => 'GET',
                    'callback' => 'mi_get_favorite_posts',
                    'permission_callback' => function ($request) {
                            if (current_user_can('edit_others_posts'))
                            return true;
                     }
                 )
            );
        });
    

    JWT Auth插件将根据标头中的标记值为user_callback函数提供用户对象,您需要做的就是在该函数内部计算一些“权限逻辑”,这将返回一个bool值 .

    在我发布的解决方案中,回调只允许访问REST endpoints ,如果访问它的用户具有'edit_others_posts'功能 - 管理员和编辑就是这种情况 .

相关问题