Logo vun Ajax Security

Ajax Security

Organisatioun
wpultimatesecurity
ajax-security

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.

Iwwersiicht

Editeurwpultimatesecurity
RepositoryWordPress-Security-Skills
Skill-Nummajax-security
Stären
54
Forks
3
Matgeliwwert Fichieren
2
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 2 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum wpultimatesecurity op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Ajax Security an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/wpultimatesecurity/WordPress-Security-Skills/tree/dev/skills/ajax-security
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wpultimatesecurity/WordPress-Security-Skills.git /tmp/WordPress-Security-Skills
mkdir -p .claude/skills
cp -r /tmp/WordPress-Security-Skills/skills/ajax-security .claude/skills/ajax-security
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Ajax Security an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Ajax Security automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Ajax Security net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

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

ReferenceLoad when
AJAX security checklistBefore final verification of AJAX security controls.
Secure AJAX handlerImplementing 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 '<div>' . $_POST['message'] . '</div>';
php
// ✅ Secure: escape at the point of output, even inside a JSON payload.
$message = sanitize_text_field( wp_unslash( $_POST['message'] ?? '' ) );
wp_send_json_success( array( 'html' => '<div>' . esc_html( $message ) . '</div>' ) );

Mistake 4 — Forgetting wp_unslash()

php
// ❌ Risky: WordPress slashes superglobals; data may contain escaped quotes.
$label = sanitize_text_field( $_POST['label'] );
php
// ✅ Secure: unslash first, then sanitize.
$label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';

Mistake 5 — Trusting is_user_logged_in() instead of a capability

php
// ❌ Insecure: every logged-in user, including subscribers, can run this.
if ( is_user_logged_in() ) {
    delete_option( 'my_plugin_config' );
}
php
// ✅ Secure: check a real capability.
if ( ! current_user_can( 'manage_options' ) ) {
    wp_send_json_error( array( 'message' => __( 'Forbidden.', 'my-plugin' ) ), 403 );
}

Mistake 6 — Unthrottled public action

php
// ❌ Insecure: anonymous endpoint, no rate limit — unbounded cost per visitor.
add_action( 'wp_ajax_nopriv_my_plugin_search', 'my_plugin_ajax_search' );
function my_plugin_ajax_search() {
    $q = isset( $_POST['q'] ) ? sanitize_text_field( wp_unslash( $_POST['q'] ) ) : '';
    wp_send_json_success( my_plugin_run_expensive_query( $q ) );
}
php
// Best-effort only: public, read-only search with bounded output.
add_action( 'wp_ajax_nopriv_my_plugin_search', 'my_plugin_ajax_search' );
function my_plugin_ajax_search() {
    if ( ! isset( $_POST['q'] ) || ! is_string( $_POST['q'] ) || strlen( $_POST['q'] ) > 200 ) {
        wp_send_json_error( array( 'message' => 'Invalid query.' ), 400 );
    }
    $q = sanitize_text_field( wp_unslash( $_POST['q'] ) );
    if ( '' === $q ) {
        wp_send_json_error( array( 'message' => 'Query required.' ), 400 );
    }
    // Fixed minute buckets; counters can race or be evicted. Not a strict quota.
    $ip     = $_SERVER['REMOTE_ADDR'] ?? '';
    $window = intdiv( time(), MINUTE_IN_SECONDS );
    $key    = 'my_plugin_rl_' . wp_hash( 'search|' . $ip . '|' . $window );
    $count  = (int) get_transient( $key );
    if ( $count >= 20 ) {
        wp_send_json_error( array( 'message' => __( 'Too many requests.', 'my-plugin' ) ), 429 );
    }
    set_transient( $key, $count + 1, MINUTE_IN_SECONDS );

    // The counter is checked before the query, never after sending the response.
    $ids = get_posts( array(
        's'           => $q,
        'post_type'   => 'post',
        'post_status' => 'publish',
        'numberposts' => 10,
        'fields'      => 'ids',
    ) );
    wp_send_json_success( $ids );
}

This read-only public search does not use a nonce as an abuse control. State-changing or privileged handlers still need their CSRF and capability checks. Fixed windows allow bursts across boundaries; parallel requests can lose counter increments, and cache eviction/storage failure can reset this best-effort counter. Do not use it as the sole control for mail sending, paid APIs, voting integrity, or brute-force defense.

REMOTE_ADDR identifies the direct peer: behind a proxy it may identify the proxy, not the visitor, and shared NATs group users together. Only trust forwarded addresses after a configured trusted proxy strips client-supplied headers and supplies a validated address; never read arbitrary X-Forwarded-For directly. Strict distributed limits need an atomic shared operation (including expiry, e.g. a Redis script), or an edge/server limiter on all relevant routes. See authentication-session-security for login-specific considerations.

Correct code examples

A complete, copy-paste-ready AJAX handler (PHP + JavaScript) is in references/secure-ajax-handler.php.

Checklist

  • The action is registered on wp_ajax_* for privileged flows or wp_ajax_nopriv_* only when the action is truly public.
  • The handler verifies the nonce with check_ajax_referer() before acting.
  • A current_user_can() check runs immediately after nonce verification.
  • Every $_POST / $_GET field is wp_unslash()-ed and sanitized to type.
  • The handler exits via wp_send_json_success(), wp_send_json_error(), or wp_die().
  • Output inside JSON responses is escaped for its context (esc_html, esc_attr, esc_url).
  • The nonce action string is specific and scoped (e.g., includes an object id).
  • Secrets are never returned to the browser or logged.
  • Abuse controls run before expensive actions; strict limits use atomic shared or edge enforcement, not transients.
  • Client identity accounts for trusted proxies/shared IPs; arbitrary forwarded headers are not trusted.

Official references

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Ajax Security?

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.

Firwat Ajax Security op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Ajax Security besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Ajax Security an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/wpultimatesecurity/WordPress-Security-Skills/tree/dev/skills/ajax-security an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Ajax Security benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Ajax Security benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Ajax Security domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Ajax Security gratis?

Jo. De Skill gëtt vum wpultimatesecurity ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇