Skip to content

Instantly share code, notes, and snippets.

@mehul0810
Created November 20, 2024 18:41
Show Gist options
  • Save mehul0810/9d07ac57774e4d07b768ea5231aa38f7 to your computer and use it in GitHub Desktop.
Save mehul0810/9d07ac57774e4d07b768ea5231aa38f7 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Secure Endpoints
* Version: 0.1
*/
add_filter('rest_authentication_errors', function ($result) {
// Allow REST API for logged-in users.
if (is_user_logged_in()) {
return $result;
}
// Allow specific endpoints needed by the Block Editor.
$allowed_routes = [
'/wp/v2/posts',
'/wp/v2/media',
'/wp/v2/categories',
'/wp/v2/tags',
'/wp/v2/users',
'/wp/v2/settings',
'/wp/v2/block-reusable'
];
$requested_route = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
foreach ($allowed_routes as $route) {
if (strpos($requested_route, $route) === 0) {
return $result; // Allow access.
}
}
// Deny access for others.
return new WP_Error(
'rest_forbidden',
__('REST API restricted.', 'your-textdomain'),
array('status' => rest_authorization_required_code())
);
});
add_filter('rest_endpoints', function ($endpoints) {
if (isset($endpoints['/wp/v2/users'])) {
$endpoints['/wp/v2/users'][0]['permission_callback'] = function () {
return current_user_can('list_users'); // Restrict access.
};
}
return $endpoints;
});
function restrict_category_permissions($permission, $request, $type) {
if ('GET' === $request->get_method() && !current_user_can('manage_categories')) {
return false; // Deny access for users without the proper capability.
}
return $permission;
}
add_filter('rest_category_item_permissions_check', 'restrict_category_permissions', 10, 3);
/**
* For Content Securit
*/
function add_security_headers() {
// Prevent ClickJacking
header("X-Frame-Options: DENY");
header("Content-Security-Policy: frame-ancestors 'none';");
// Prevent MIME Type Sniffing
header("X-Content-Type-Options: nosniff");
// Enforce HTTPS with HSTS
header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
// Add Content Security Policy (adjust based on your needs)
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'self'; frame-src 'none';");
}
add_action('send_headers', 'add_security_headers');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment