#53008 closed defect (bug) (wontfix)
Creating an anonymous comment with custom fields via REST API
Reported by: | dawgawel | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | 4.7 |
Component: | REST API | Keywords: | close |
Focuses: | rest-api | Cc: |
Description
Hi!
When rest_allow_anonymous_comments
filter is enabled, I'm able to successfully create anonymous comments via REST API POST /comments method, without any authorization. Unfortunately, when trying to create a comment with a registered, non-protected meta field, I got a 401 error (details below). Even when auth_callback
is forced to return true for that field, things don't change. I think that by default, when rest_allow_anonymous_comments
is enabled, one should be able to create a comment with meta fields.
Field definition:
<?php add_filter( 'rest_allow_anonymous_comments', '__return_true' ); register_meta('comment', 'twitter_handle', [ 'single' => true, 'type' => 'string', 'show_in_rest' => true, ]);
Request:
curl --request POST \ --url 'http://example.com/wp-json/wp/v2/comments' \ --header 'Content-Type: application/json' \ --data '{ "post": 1, "content": "Lorem ipsum", "author_name": "Dawid", "author_email": "example@example.com", "meta": { "twitter_handle": "dmgawel" } }'
Response:
{ "code": "rest_cannot_update", "message": "Sorry, you are not allowed to edit the twitter_handle custom field.", "data": { "key": "twitter_handle", "status": 401 } }
I got the same response for the following meta field definition:
<?php add_filter( 'rest_allow_anonymous_comments', '__return_true' ); register_meta('comment', 'twitter_handle', [ 'single' => true, 'type' => 'string', 'show_in_rest' => true, 'auth_callback' => function(){ return true; } ]);
Change History (5)
#2
@
4 years ago
Hi @TimothyBlynJacobs, thanks for a quick response :)
While I still think that permission for creating comments with meta, when rest_allow_anonymous_comments
is enabled, is a more intuitive behavior, I totally understand that underlying architecture may not allow such implementation or make it complicated/unsecure.
I'll implement creation logic with register_rest_field
then. Thank you.
You can close the ticket (I'm not sure which resolution status you'd like to select).
Thanks for the ticket @dawgawel and welcome to trac!
The issue is that the
auth_callback
for a meta key is applied on top of verifying that the user has access to edit the object itself, https://github.com/WordPress/wordpress-develop/blob/234c2b52ccf584cb93dce0eaf17431310b1d7458/src/wp-includes/capabilities.php#L309I don't think we could really change this without opening up security issues. Instead, I'd recommend to use
register_rest_field
which will allow you to use any updating logic you'd like.