Performance: Authentication for API
This affects the time it takes for the API to respond and the initial page load speed when fetching data from the API.
function call_api_with_jwt() {
$token = get_transient('jwt_token');
if (!$token) {
$response = wp_remote_post('https://example.com/wp-json/jwt-auth/v1/token', array(
'body' => array('username' => 'user', 'password' => 'password')
));
$body = json_decode(wp_remote_retrieve_body($response));
$token = $body->token;
set_transient('jwt_token', $token, 3600);
}
$response = wp_remote_get('https://example.com/wp-json/wp/v2/posts', array(
'headers' => array('Authorization' => 'Bearer ' . $token)
));
return wp_remote_retrieve_body($response);
}function call_api_with_basic_auth() {
$response = wp_remote_get('https://example.com/wp-json/wp/v2/posts', array(
'headers' => array('Authorization' => 'Basic ' . base64_encode('user:password'))
));
return wp_remote_retrieve_body($response);
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Basic Auth on every request | Minimal | 0 | Low | [X] Bad |
| JWT token caching | Minimal | 0 | Low | [OK] Good |
permission_callback in WordPress REST API authentication?permission_callbackpermission_callback specifically controls access.permission_callback, which should be set to a callable that returns true or false.permission_callback with a valid callable __return_true allowing access.register_rest_route('myplugin/v1', '/secret', array(
'methods' => 'GET',
'callback' => 'get_secret_data',
'permission_callback' => function() {
return current_user_can('read');
}
));
function get_secret_data() {
return 'Secret Info';
}register_rest_route('myplugin/v1', '/info', array(
'methods' => 'GET',
'callback' => 'get_info',
'permission_callback' => 'current_user_can('read')'
));
function get_info() {
return 'Info';
}permission_callback implementations correctly enforces this?current_user_can('read') which many users have but not 'edit_posts'. D allows everyone.Pass the test and this pattern moves unknown