WordPress v6.1.1
rest_authentication_errors
フィルターを使う
apply_filters( 'rest_authentication_errors', WP_Error|null|true $errors )
This is used to pass a WP_Error from an authentication method back to the API.Authentication methods should check first if they’re being used, as multiple authentication methods can be enabled on a site (cookies, HTTP basic auth, OAuth). If the authentication method hooked in is not actually being attempted, null should be returned to indicate another authentication method should check instead.
$errors
WP_Error if authentication error, null if authentication method wasn't used, true if authentication succeeded.
cf. rest_authentication_errors | Hook | WordPress Developer Resources
null
… 認証のチェックがまだされていないboolean
… 認証のチェック済みtrue
… 認証に成功false
… 認証に失敗
WP_Error
… エラーが発生
WordPress の REST API で認証を確認するために通過する箇所へのフィルター
この箇所で WP_Error
を返すことで全ての API をエラーにすることができるという事っぽい
<?php function disable_rest_api() { return new WP_Error( 'disabled', 'REST API is disabled.', array( 'status' => rest_authorization_required_code() ) ); } add_filter( 'rest_authentication_errors', 'disable_rest_api' );
API にアクセスするとエラーメッセージが返ってくる
/wp-json/wp/v2/posts
{"code":"disabled","message":"REST API is disabled.","data":{"status":403}}
/wp-json/wp/v2/users
{"code":"disabled!","message":"REST API is disabled.","data":{"status":403}}
できた ( ᐢ˙꒳˙ᐢ )
📝 Tips: WordPress v4.7.0 から rest_enabled
を使う方法は非推奨になっている
<?php add_filter( 'rest_enabled', '__return_false' );
上記のコードは下記の notice が表示される
Deprecated: フック rest_enabled は、バージョン 4.7.0 から非推奨になりました ! 代わりに rest_authentication_errors を使用してください。 REST API を完全に無効化することはできなくなりました。代わりに rest_authentication_errors フィルターを使って API へのアクセスを制限できます。
📝 Tips: rest_endpoints
フィルターで API をカスタマイズする方法
rest_endpoints
フィルターで REST API のエンドポイントをカスタマイズできる。その中で API を無効化にする方法
<?php function filter_rest_endpoints() { if ( isset( $endpoints['/wp/v2/users'] ) ) { unset( $endpoints['/wp/v2/users'] ); } if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) { unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ); } return $endpoints; } add_filter( 'rest_endpoints', 'filter_rest_endpoints', 10, 1 );
とりあえずまるっと無効化してしまうなら rest_authentication_errors
フィルターで良さそう
おわり ₍ ᐢ. ̫ .ᐢ ₎
[参考]