Authenticating with REST API

时间:2019-08-06 作者:Jonathan Tuzman

我尝试了各种方法来验证post请求。

WP用户插件-根据docs, 我已登录wp-json/wpuser/v1/user/login 收到了我的令牌。我已将该令牌作为名为“Authorization”(也尝试了“Authorization”)的标头传递给wp-json/wp/v2/job-listings/ 我明白了401: rest_cannot_create. 我也试过这个authorization 作为参数,以及h:authorization, 还有大写字母“A”。

JSON API插件-使用生成nonceget_nonce/?controller=auth&method=generate_auth_cookie, 使用生成cookieauth/generate_auth_cookie 使用nonce和凭据,尝试使用cookie和nonce作为X-WP-Nonce 标题。两者都返回403: rest_cookie_invalid_nonce

已尝试添加RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] 给我的.htacces 并尝试了上述操作。

我不想使用基本的Auth插件,因为它存在安全问题(相信我,我过去试过,但没有用)。

无论您做什么,请不要简单地将WP REST API手册链接到我这里。我已经读过了,我不知道从哪里可以得到nonce,所以我欢迎对此进行实际解释,但请不要只是将我链接到该页面。

如果有必要,我很乐意添加一些服务器代码,但这些插件意味着我不必这样做。

请帮忙。非常感谢。

2 个回复
SO网友:Tom J Nowell

You don\'t need plugins for authentication unless you\'re making a cross domain request, and to get the nonce, you just create it as you would any other nonce.

As the handbook states:

For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress.

So lets do that:

$nonce = wp_create_nonce( \'wp_rest\' );

There\'s nothing special about how the nonce gets created, it\'s created the same way as every other nonce in WordPress. You would use the same function to put nonces on your action buttons and in your forms to improve security.

Now we just put it in our doc in a way javascript can access it. Luckily the handbook gives us a working code example:

https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

<?php
wp_localize_script( \'wp-api\', \'wpApiSettings\', array(
    \'root\' => esc_url_raw( rest_url() ),
    \'nonce\' => wp_create_nonce( \'wp_rest\' )
) );

Followed by a working example of using the nonce in jQuery for an authenticated POST request:

$.ajax( {
    url: wpApiSettings.root + \'wp/v2/posts/1\',
    method: \'POST\',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( \'X-WP-Nonce\', wpApiSettings.nonce );
    },
    data:{
        \'title\' : \'Hello Moon\'
    }
} ).done( function ( response ) {
    console.log( response );
} );

If you enqueue the built in backbone based REST library, it will automatically generate the nonce using the same code above.

This will work when combined with a cookie for a logged in user, however, it will not work for requests across domains.

If you\'re trying to make a REST API request from another website, a CLI app, mobile app, a Node application, etc etc you will need a custom authentication plugin. You will need to consult with their documentation and support avenues though as 3rd party plugin dev support is offtopic on this stack

SO网友:OctaviaLo

如果任何人正在使用Fetch寻找解决方案:

 window
.fetch(`${scriptVars.endpoint}`, {
  method: \'POST\',
  headers: {
    \'Content-Type\': \'application/json\',
    \'X-WP-Nonce\': scriptVars.nonce
  },
  credentials: \'same-origin\',
  body: JSON.stringify(postData)
})
.then(() => window.alert(\'success\'));