File: /var/www/linde/wp-content/plugins/lindevr-site-plugin/rest.php
<?php
/**
* Restricts access to the WordPress REST API, allowing only authenticated users
* except for specific public routes.
*
* This function hooks into `rest_authentication_errors` to enforce authentication
* using Application Passwords . new feature in Wordpress since version 5.9
* It blocks all API requests unless:
* - The user is logged in.
* - The request contains valid authentication credentials.
* - The requested route is explicitly allowed as a public endpoint.
*/
function linde_protect_rest_api( $result ) {
// Allow access if a previous authentication succeeded
if (true === $result || is_wp_error($result)) {
return $result;
}
if (is_user_logged_in()) {
// If the user is logged in and authenticated, skip further checks
return $result;
}
// Get the current REST route being accessed
$current_route = $_SERVER['REQUEST_URI'];
// Get the request method (GET, POST, OPTIONS, etc.)
$request_method = $_SERVER['REQUEST_METHOD'];
// The checkVersion method should be public
$public_route = '/wp-json/linde-vr-video/v1/checkVersion';
if ($request_method === 'OPTIONS') {
return true;
}
// If the requested route matches the public route, allow access
if (strpos($current_route, $public_route) === 0) {
return true;
}
// Define your hardcoded Bearer token here
$expected_token = SITE_API_TOKEN;
// Get the Authorization header (case-insensitive)
$headers = getallheaders();
// Check if the Authorization header exists
if (!isset($headers['Authorization'])) {
return new WP_Error('rest_forbidden', __('No authorization header present.'), array('status' => 401));
}
// Extract the token from the header
$auth_header = trim($headers['Authorization']);
$matches = [];
if (!preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
return new WP_Error('rest_forbidden', __('Invalid authorization header format.'), array('status' => 401));
}
$token = $matches[1];
// Compare the token
if ($token !== $expected_token) {
return new WP_Error('rest_forbidden', __('Invalid token.'), array('status' => 403));
}
// Token is valid, allow access
return $result;
}
add_filter( 'rest_authentication_errors', 'linde_protect_rest_api' );
?>