Disable rest api wordpress

Disable WP REST API

Description

This plugin does one thing: disables the WP REST API for visitors who are not logged into WordPress. No configuration required.

This plugin works with only 22 short lines of code (less than 2KB). So it is super lightweight, fast, and effective.

Features

  • Disable REST/JSON for visitors (not logged in)
  • Disables REST header in HTTP response for all users
  • Disables REST links in HTML head for all users
  • 100% plug-and-play, set-it-and-forget solution

The fast, simple way to prevent abuse of your site’s REST/JSON API

How does it work? That depends on which version of WordPress you are using..

WordPress v4.7 and beyond

For WordPress 4.7 and better, this plugin completely disables the WP REST API unless the user is logged into WordPress.

  • For logged-in users, WP REST API works normally
  • For logged-out users, WP REST API is disabled

What happens if logged-out visitor makes a JSON/REST request? They will get only a simple message:

“rest_login_required: REST API restricted to authenticated users.”

This message may customized via the filter hook, disable_wp_rest_api_error . Check out this post for an example of how to do it.

Older versions of WordPress

For WordPress versions less than 4.7, this plugin simply disables all REST API functionality for all users.

More information available below in the FAQs section.

Privacy

This plugin does not collect or store any user data. It does not set any cookies, and it does not connect to any third-party locations. Thus, this plugin does not affect user privacy in any way. If anything it improves user privacy, as it protects potentially sensitive information from being displayed/accessed via REST API.

Disable WP REST API is developed and maintained by Jeff Starr, 15-year WordPress developer and book author.

Support development of this plugin

I develop and maintain this free plugin with love for the WordPress community. To show support, you can make a donation or purchase one of my books:

And/or purchase one of my premium WordPress plugins:

  • BBQ Pro – Super fast WordPress firewall
  • Blackhole Pro – Automatically block bad bots
  • Banhammer Pro – Monitor traffic and ban the bad guys
  • GA Google Analytics Pro – Connect WordPress to Google Analytics
  • Simple Ajax Chat Pro – Unlimited chat rooms
  • USP Pro – Unlimited front-end forms

Links, tweets and likes also appreciated. Thank you! 🙂

Installation

How to Install

  1. Upload the plugin to your blog and activate
  2. Done! No further configuration is required.

Testing

To test that the plugin is working, log out of WordPress and then request https://example.com/wp-json/ in a browser. See FAQs for more infos.

Like the plugin?

If you like Disable WP REST API, please take a moment to give a 5-star rating. It helps to keep development and support going strong. Thank you!

What is the default access-denied message?

When the user is logged in to WordPress, the normal REST API data will be displayed. When the user is not logged in, this is the default message:

Why would anyone want to disable the REST API?

Technically this plugin only disables REST API for visitors who are not logged into WordPress. With that in mind, here are some good reasons why someone would want to disable REST API for non-logged users:

  • The REST API may not be needed for non-logged users
  • Disabling the REST API conserves server resources
  • Disabling the REST API minimizes potential attack vectors
  • Disabling the REST API prevents content scraping and plagiarism
Читайте также:  Как почистить пищевой принтер кэнон

I’m sure there are other valid reasons, but you get the idea 🙂

There already is another “Disable REST” plugin?

Yep, actually there are two other “Disable REST” plugins:

The first of those plugins is awesome and provides a LOT more features and functionality than is required to simply disable REST. And the second plugin was shut down due to lack of use. I wrote my disable-REST plugin because I wanted something super lightweight, fast, and effective. If you are looking for more options and features, then check out the first of those two listed alternatives.

How do I test that REST is disabled?

Testing is easy:

  1. Log out of WordPress
  2. Using a browser, request https://example.com/wp-json/

If you see the following message, REST is disabled:

“rest_login_required: REST API restricted to authenticated users.”

Then if you log back in and make a new request for https://example.com/wp-json/ , you will see that REST is working normally.

Does it disable REST functionality added by other plugins?

Yes, if the REST endpoints are registered with the WP REST API.

Does this work with Gutenberg/Block Editor?

Yes. It works the same regardless of which editor (Classic or Block) you are using.

How to customize the error message?

By default the plugin displays a message for unauthenticated users: “REST API restricted to authenticated users.” To customize that message to whatever you want, add the following code via functions.php or simple custom plugin:

How to allow access for Contact Form 7?

As explained in this thread, the plugin Contact Form 7 requires REST API access in order for the contact form to work. To allow for this, you can install our free plugin to allow REST access for CF7. Learn more and download at Perishable Press. When used together with the Disable REST API plugin, the CF7 addon will enable sending emails to work again.

Got a question?

Send any questions or feedback via my contact form

Источник

Как отключить/закрыть REST API от публичного доступа?

Я уже отвечал на вопрос как полностью отключить REST API.

Однако разработчики WordPress настоятельно НЕ рекомендуют полностью отключать REST API, потому что это поломает работоспособность WordPress в админке с 5 версии, REST там используется для Блочного редактора контента записи.

Чтобы оставить REST API работоспособным, но при этом закрыть все маршруты от публичного доступа, можно использовать хуки. Тут есть несколько вариантов:

Вариант 1:

Код можно вставить в файл темы functions.php или куда-либо еще.

Этот код разрешает доступ к REST API только для авторизованных пользователей с правами редактора и выше.

Проверку ! current_user_can(‘edit_others_posts’) можно заменить на более подходящую для вашего сайта. Например, её можно упростить и сделать REST API доступным для всех авторизованных пользователей (неважно какие права). Для этого замените проверку на ! is_user_logged_in() .

ВАЖНО! Закрывать маршруты таким образом опасно, потому что на сайте могут быть маршруты для пользователей, например сабмит формы на фронте. Этот метод закроет абсолютно все маршруты в том числе и те, которые могут быть созданы плагинами или темой для неавторизованных пользователей. Поэтому рекомендую использовать вариант ниже через хук rest_pre_dispatch, он позволяет закрыть указанные маршруты и не трогать остальные.

Вариант 2:

Очень похож на первый, но там у нас нет доступа к запросу и классу REST сервера.

Сразу же после хука rest_authentication_errors (если проверка пройдена), запускается метод
WP_REST_Server::dispatch() и в его начале срабатывает хук rest_pre_dispatch . Технически это точно такой же хук, на котором можно вернуть WP_Error и любой рест запрос увидит эту ошибку. Т.е. первый вариант мы можем записать следующим кодом, в котором нам будут доступны объект сервера ($rest_server) и объект запроса ($request).

Источник

Disable REST API

Description

The most comprehensive plugin for controlling access to the WordPress REST API!

Works as a “set it and forget it” install. Just upload and activate, and the entire REST API will be inaccessible to your general site visitors.

But if you do need to grant access to some endpoints, you can do that too. Go to the Settings page and you can quickly whitelist individual endpoints (or entire branches of endpoints) in the REST API.

You can even do this on a per-user-role basis, so your unauthenticated users have one set of rules while WooCommerce customers have another while Subscribers and Editors and Admins all have their own. NOTE: Out of the box, all defined user roles will still be granted full access to the REST API until you choose to manage those settings.

Читайте также:  Using postgresql from python

For most versions of WordPress, this plugin will return an authentication error if a user is not allowed to access an endpoint. For legacy support, WordPress 4.4, 4.5, and 4.6 use the provided rest_enabled filter to disable the entire REST API.

Screenshots

  • The JSON returned by a website with the API disabled via filters (WP versions 4.4, 4.5, 4.6)
  • The JSON returned by a website with the API disabled via authentication methods (WP versions 4.7+)
  • The Settings page lets you selectively whitelist endpoints registered with the REST API, on a per-user-role basis.

Installation

  1. Upload the disable-json-api directory to the /wp-content/plugins/ directory via FTP
  2. Alternatively, upload the disable-json-api_v#.#.zip file to the ‘Plugins->Add New’ page in your WordPress admin area
  3. Activate the plugin through the ‘Plugins’ menu in WordPress

How do I know if this plugin is working?

While logged into WordPress as any user, the REST API will function as intended. Because of this, you must use a new browser – or Chrome’s incognito mode – to test your website with a clean session. Go to yourdomain.com/wp-json/ (or yourdomain.com/?rest_route=/ if you have pretty permalinks disabled) while NOT LOGGED IN to test the results. You will see an authentication error returned if the plugin is active. “DRA: Only authenticated users can access the REST API.”

Does this plugin disable every REST API that is installed on my site?

This plugin is ONLY meant to disable endpoints accessible via the core REST API that is part of WordPress itself. If a plugin or theme has implemented their own REST API (not to be confused with implementing their own endpoints within the WordPress API) this plugin will have no effect.

Источник

Как отключить REST API WordPress?

Хотите очистить лишний код на сайте ВордПресс и повысить его безопасность? Отличная идея отключить REST API WordPress. Разберем все способы как это сделать.

REST API WordPress – что это и как работает?

Как мы писали в одной из прошлых статей, это инструмент, который позволяет сайту взаимодействовать с внешними источниками. Например, можно управлять созданием и публикацией контента без входа в административную панель. Интерфейс REST API появился, начиная с версии WP 4.7, и был включен в ядро. Основан на JSON (JavaScript Object Notation) – языке, предназначенном для отправки, получения и хранения данных.

Зачем отключать?

Есть несколько причин. Если для работы с ВП-сайтом вы используете только админку и хотите повысить безопасность своего ресурса.

Как отключить?

Рассмотрим рабочие способы.

Плагин Disable REST API

Плагин Disable REST API работает “из коробки”. Не нужно ничего настраивать. Достаточно просто установить и активировать.

Плагин Clearfy Pro

Если у вас установлено это расширение, в админ-панели откройте Clearfy Pro и перейдите на вкладку Код. Напротив опции Отключить JSON REST API передвиньте вправо ползунок и нажмите кнопку Сохранить изменения.

Активировать промокод на 15%

Вручную

Если не хотите на свой сайт устанавливать дополнительные плагины, этот способ для вас.

Найдите и откройте основной конфигурационный файл вашей активной WordPress-темы functions.php. В самый конец просто добавьте этих несколько строк:

Если вы не знаете, как редактировать functions.php, то в этом случае Вам поможет плагин ProFunctions.

Нажмите, пожалуйста, на одну из кнопок, чтобы узнать понравилась статья или нет.

Источник

Disable WP REST API

Описание

This plugin does one thing: disables the WP REST API for visitors who are not logged into WordPress. No configuration required.

This plugin works with only 22 short lines of code (less than 2KB). So it is super lightweight, fast, and effective.

Features

  • Disable REST/JSON for visitors (not logged in)
  • Disables REST header in HTTP response for all users
  • Disables REST links in HTML head for all users
  • 100% plug-and-play, set-it-and-forget solution

The fast, simple way to prevent abuse of your site’s REST/JSON API

How does it work? That depends on which version of WordPress you are using..

WordPress v4.7 and beyond

For WordPress 4.7 and better, this plugin completely disables the WP REST API unless the user is logged into WordPress.

  • For logged-in users, WP REST API works normally
  • For logged-out users, WP REST API is disabled

What happens if logged-out visitor makes a JSON/REST request? They will get only a simple message:

«rest_login_required: REST API restricted to authenticated users.»

Читайте также:  Картридж для кэнон mf411dw

This message may customized via the filter hook, disable_wp_rest_api_error . Check out this post for an example of how to do it.

Older versions of WordPress

For WordPress versions less than 4.7, this plugin simply disables all REST API functionality for all users.

More information available below in the FAQs section.

Privacy

This plugin does not collect or store any user data. It does not set any cookies, and it does not connect to any third-party locations. Thus, this plugin does not affect user privacy in any way. If anything it improves user privacy, as it protects potentially sensitive information from being displayed/accessed via REST API.

Disable WP REST API is developed and maintained by Jeff Starr, 15-year WordPress developer and book author.

Support development of this plugin

I develop and maintain this free plugin with love for the WordPress community. To show support, you can make a donation or purchase one of my books:

And/or purchase one of my premium WordPress plugins:

  • BBQ Pro — Super fast WordPress firewall
  • Blackhole Pro — Automatically block bad bots
  • Banhammer Pro — Monitor traffic and ban the bad guys
  • GA Google Analytics Pro — Connect WordPress to Google Analytics
  • Simple Ajax Chat Pro — Unlimited chat rooms
  • USP Pro — Unlimited front-end forms

Links, tweets and likes also appreciated. Thank you! 🙂

Установка

How to Install

  1. Upload the plugin to your blog and activate
  2. Done! No further configuration is required.

Testing

To test that the plugin is working, log out of WordPress and then request https://example.com/wp-json/ in a browser. See FAQs for more infos.

Like the plugin?

If you like Disable WP REST API, please take a moment to give a 5-star rating. It helps to keep development and support going strong. Thank you!

Часто задаваемые вопросы

What is the default access-denied message?

When the user is logged in to WordPress, the normal REST API data will be displayed. When the user is not logged in, this is the default message:

Why would anyone want to disable the REST API?

Technically this plugin only disables REST API for visitors who are not logged into WordPress. With that in mind, here are some good reasons why someone would want to disable REST API for non-logged users:

  • The REST API may not be needed for non-logged users
  • Disabling the REST API conserves server resources
  • Disabling the REST API minimizes potential attack vectors
  • Disabling the REST API prevents content scraping and plagiarism

I’m sure there are other valid reasons, but you get the idea 🙂

There already is another «Disable REST» plugin?

Yep, actually there are two other «Disable REST» plugins:

The first of those plugins is awesome and provides a LOT more features and functionality than is required to simply disable REST. And the second plugin was shut down due to lack of use. I wrote my disable-REST plugin because I wanted something super lightweight, fast, and effective. If you are looking for more options and features, then check out the first of those two listed alternatives.

How do I test that REST is disabled?

Testing is easy:

  1. Log out of WordPress
  2. Using a browser, request https://example.com/wp-json/

If you see the following message, REST is disabled:

«rest_login_required: REST API restricted to authenticated users.»

Then if you log back in and make a new request for https://example.com/wp-json/ , you will see that REST is working normally.

Does it disable REST functionality added by other plugins?

Yes, if the REST endpoints are registered with the WP REST API.

Does this work with Gutenberg/Block Editor?

Yes. It works the same regardless of which editor (Classic or Block) you are using.

How to customize the error message?

By default the plugin displays a message for unauthenticated users: «REST API restricted to authenticated users.» To customize that message to whatever you want, add the following code via functions.php or simple custom plugin:

How to allow access for Contact Form 7?

As explained in this thread, the plugin Contact Form 7 requires REST API access in order for the contact form to work. To allow for this, you can install our free plugin to allow REST access for CF7. Learn more and download at Perishable Press. When used together with the Disable REST API plugin, the CF7 addon will enable sending emails to work again.

Got a question?

Send any questions or feedback via my contact form

Источник

КомпСовет