Nonce validation in REST API

In a headless WordPress setup where you are using JWT for authentication, the standard nonce mechanism provided by wp may not directly fit your needs, especially when dealing with preview functionality. The nonce generated by wp is typically tied to the users session, which is not compatible with JWT authentication.

One approach to solve this issue is to create a custom nonce mechanism that works with your JWT authentication

// Step 1: Custom endpoint to generate nonce
add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/nonce', array(
        'methods' => 'GET',
        'callback' => 'generate_custom_nonce',
        'permission_callback' => function () {
            return current_user_can('read'); // Adjust permission as needed
        }
    ));
});

function generate_custom_nonce(WP_REST_Request $request) {
    // Generate nonce based on user's JWT token
    $user_id = get_current_user_id();
    $nonce = wp_create_nonce('custom_action_' . $user_id);
    
    return rest_ensure_response($nonce);
}

// Step 2: Validate nonce in requests
add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/preview', array(
        'methods' => 'GET',
        'callback' => 'get_preview_data',
        'permission_callback' => function () {
            return current_user_can('read'); // Adjust permission as needed
        }
    ));
});

function get_preview_data(WP_REST_Request $request) {
    $nonce = $request->get_header('X-Custom-Nonce'); // Get nonce from header
    $valid_nonce = wp_verify_nonce($nonce, 'custom_action_' . get_current_user_id());
    
    if (!$valid_nonce) {
        return new WP_Error('invalid_nonce', 'Invalid nonce.', array('status' => 403));
    }

    // Proceed to fetch preview data
    // Your code to fetch and return preview data
}

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)