If you’re using the WordPress REST API, you may want to protect certain endpoints from unauthenticated access. The user endpoint is particularly sensitive, as it can contain sensitive information such as email addresses and usernames. In this blog post, we’ll show you a simple code snippet that you can use to prevent unauthenticated access to the user endpoint.
The code snippet uses the rest_authentication_errors
filter to check if the current request is for the user endpoint. If it is, the code checks if the current user has the list_users
capability. If the user doesn’t have the capability, the code returns a WP_Error
with the message “Access is only for authenticated users” and a status code of 401 (unauthorised).
Here’s the code:
/**
* Prevent unauthenticated access to the user REST API endpoint
*/
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
global $wp;
if ( $wp->request === 'wp-json/wp/v2/users' && false === current_user_can('list_users') ) {
return new \WP_Error( 'rest_not_logged_in', 'Access is only for authenticated users', array( 'status' => 401 ) );
}
return $result;
});
To use this code, simply add it to your WordPress theme’s functions.php
file or in a custom plugin. This code will prevent unauthenticated users from accessing the user endpoint in the WordPress REST API.
In conclusion, protecting your user endpoint in the WordPress REST API is important to prevent unauthorised access to sensitive information. This code snippet provides a simple solution that you can easily implement in your WordPress website.