处理 WordPress RESTfull API(WP API) 中的用户认证,发送 POST 请求

来源:互联网 发布:php的mvc 编辑:程序博客网 时间:2024/06/03 20:00

WordPress RESTful API 插件支持3种用户认证方式,分别是:Cookie 认证、Oauth 认证和基本 HTTP认证。通过 RESTful API 获取信息时,这种认证是不需要的,直接获取就可以了。只有在发送信息(POST)到 API 的时候才需要用户认证,否则将返回HTTP 403 未授权错误。今天我们来介绍一下最简单的 Cookie 认证方式。

认证的原理是使用 wp nonces 来确保POST请求是合法的站内请求,而不是其他客户端发送的。

首先,通过 wp_create_nonce 自动生成 nonce Cookie 信息

function enqueue_scripts_styles_init() {wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/js/script.js', array('jquery'), 1.0 );wp_localize_script( 'ajax-script', 'WP_API_Settings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );}add_action('init', 'enqueue_scripts_styles_init');

添加 nonce 信息到 POST 请求中

//添加请求配置var xhrConfig = function (xhr) {    xhr.setRequestHeader("X-WP-Nonce", WP_API_Settings.nonce);};//模型var posts_add = {    //获取数据,初始化数据    getData: function () {        return {            title: m.prop(""),            content: m.prop(""),            saved: m.prop(false),            error: m.prop("")        }    },    //设置数据,保存表单的数据    setData: function (data) {        return m.request({                method: "POST",                url: "/wp-json/wp/v2/posts/",                config: xhrConfig,                data: {                    title: data.title(),                    content: data.content()                }            })            .then(data.saved.bind(this, true), data.error)    }};

以上代码是基于 Mathril 的,使用其他前端框架或者在后端发送POST请求到RESTful 的认证方法是一样的,文中的代码仅供参考。Oauth 认证和基本 HTTP认证的方法大家可以参考官方文档,如果我有机会测试,也会及时发布文章说明使用方法。

0 0
原创粉丝点击