--- name: ajax-security description: > Use when registering or handling WordPress AJAX over admin-ajax.php - wp_ajax_{action} / wp_ajax_nopriv_{action} hooks, JavaScript that posts to admin_url('admin-ajax.php'), or wp.apiFetch / fetch calls to custom actions. Verifies the nonce with check_ajax_referer, gates the action with current_user_can, unslashes and sanitizes every field, and replies with wp_send_json_success / wp_send_json_error. Prevents CSRF, broken access control, and injection on the AJAX surface. compatibility: "Examples generally use PHP 7.4 syntax; check each API against target WordPress/PHP versions. Use maintained WordPress and supported PHP in production. Shell examples require their named tools." license: MIT metadata: tags: "wordpress, security, php, javascript, ajax, csrf, nonce" --- # AJAX security ## When to use this skill Use this skill whenever code registers or handles an AJAX action through WordPress's `admin-ajax.php` endpoint: - `add_action( 'wp_ajax_{action}', ... )` for logged-in users. - `add_action( 'wp_ajax_nopriv_{action}', ... )` for logged-out visitors. - JavaScript posting to `admin_url( 'admin-ajax.php' )` with jQuery, `fetch`, or `wp.apiFetch`. - Returning JSON, HTML fragments, or any server-computed data from an AJAX handler. If the request changes state or exposes privileged data, it needs a nonce **and** a capability check. `wp_ajax_nopriv_*` is intentionally unauthenticated — never use it for admin actions. Related: see the `nonces-csrf-protection` skill for the full nonce lifecycle and the `rest-api-security` skill for REST endpoints. ## Core principles (and why they matter) 1. **`wp_ajax_*` vs `wp_ajax_nopriv_*` are different trust boundaries.** `nopriv` fires for anonymous visitors; use it only for truly public actions. Privileged actions must use `wp_ajax_*`. 2. **Nonce + capability for privileged actions.** `check_ajax_referer()` checks a CSRF token, not authenticated origin or authorization; `current_user_can()` checks permission. 3. **Sanitize every input field.** `$_POST` values in AJAX are just as attacker-controllable as any other request. `wp_unslash()` then sanitize to type before use. 4. **Exit through `wp_send_json_*` or `wp_die()`.** Never echo raw output and fall through. JSON responses keep the contract explicit and prevent accidental HTML/PHP leakage. 5. **Scope the nonce to the action.** A nonce for `my_plugin_delete_item_42` cannot be replayed to delete item 99. 6. **Fail closed.** Any failed check returns a JSON error or dies; the handler never continues to act. 7. **Throttle anonymous and expensive actions before the work.** Public nonces can be obtained and replayed by attackers; they are not rate limits. Transient counters are best-effort load shedding only: read/increment/write is non-atomic and cached entries can disappear early. Strict limits need an atomic shared backend or an edge/server limiter with defined windows, trusted client identity, and failure policy. ## Step-by-step implementation 1. Register the handler with the correct hook (`wp_ajax_*` for authenticated, `wp_ajax_nopriv_*` for public). 2. Enqueue the script and pass the AJAX URL + nonce via `wp_localize_script()` or `wp_add_inline_script()`. 3. In the handler, verify the nonce first with `check_ajax_referer( $action, $query_arg, false )`. Passing `false` lets you return a clean JSON error instead of dying with `-1`. 4. Check `current_user_can()` immediately after the nonce. 5. `wp_unslash()` and sanitize every `$_POST` / `$_GET` field, using the right sanitizer for the type (`absint`, `sanitize_text_field`, `sanitize_key`, `sanitize_email`, etc.). 6. Enforce the abuse policy **before** queries, mail, or other expensive actions; return `wp_send_json_error( ..., 429 )` when rejected. Use an atomic limiter where bypass would create a security or cost risk; a transient is only a best-effort supplement. 7. Perform the authorized action. 8. Return `wp_send_json_success()` or `wp_send_json_error()` and stop. ### Supporting references | Reference | Load when | | --- | --- | | [AJAX security checklist](references/checklist.md) | Before final verification of AJAX security controls. | | [Secure AJAX handler](references/secure-ajax-handler.php) | Implementing the privileged admin-ajax.php profile-update flow with nonce, capability, input validation, and JSON responses. | ## Common AI mistakes / anti-patterns ### Mistake 1 — No nonce verification ```php // ❌ Insecure: any site can POST to this action and trigger the handler. add_action( 'wp_ajax_my_plugin_vote', function () { $post_id = absint( $_POST['post_id'] ); update_post_meta( $post_id, '_votes', get_post_meta( $post_id, '_votes', true ) + 1 ); wp_send_json_success(); } ); ``` ```php // ✅ Secure: verify nonce, then capability, then act. add_action( 'wp_ajax_my_plugin_vote', 'my_plugin_ajax_vote' ); function my_plugin_ajax_vote() { if ( ! check_ajax_referer( 'my_plugin_vote', 'nonce', false ) ) { wp_send_json_error( array( 'message' => __( 'Security check failed.', 'my-plugin' ) ), 403 ); } if ( ! current_user_can( 'edit_posts' ) ) { wp_send_json_error( array( 'message' => __( 'Forbidden.', 'my-plugin' ) ), 403 ); } $post_id = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0; if ( $post_id <= 0 ) { wp_send_json_error( array( 'message' => __( 'Invalid post.', 'my-plugin' ) ), 400 ); } update_post_meta( $post_id, '_votes', get_post_meta( $post_id, '_votes', true ) + 1 ); wp_send_json_success(); } ``` ### Mistake 2 — Using `wp_ajax_nopriv_*` for a privileged action ```php // ❌ Insecure: anonymous users can now save settings. add_action( 'wp_ajax_nopriv_my_plugin_save_settings', 'my_plugin_save_settings' ); ``` ```php // ✅ Secure: privileged actions use wp_ajax_* only. add_action( 'wp_ajax_my_plugin_save_settings', 'my_plugin_save_settings' ); function my_plugin_save_settings() { check_ajax_referer( 'my_plugin_save_settings', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Forbidden.', 'my-plugin' ) ), 403 ); } // ...sanitize + save... wp_send_json_success(); } ``` ### Mistake 3 — Echoing raw `$_POST` or building HTML without escaping ```php // ❌ Insecure: reflected XSS. echo '