WordPress JWT Authentication: Stateless API Auth Without Cookies

JWT authentication for the WordPress REST API: when it fits and how to do it safely

Cookies and nonces authenticate REST requests from the WordPress site itself. A mobile app or a separate frontend needs something else. WordPress core has Application Passwords since 5.6, which work with Basic Auth over HTTPS. JSON Web Tokens are the other common choice: a short-lived signed token, issued after login, that the client sends in the Authorization header. JWT is not more secure by itself; it fits when tokens must expire quickly and the client cannot store a long-lived password.

Problem: A mobile app for a membership site lets members log in and read protected content through the REST API. Storing an Application Password on the phone means a permanent credential, and the team found a JWT tutorial that signs tokens with a hard-coded secret and never expires them.

Solution: Issue a short-lived access token (15 minutes) signed with HS256 and a secret from wp-config.php, together with a longer-lived refresh token that is stored hashed in user meta and can be revoked. Validate the token in the determine_current_user filter, verify signature, expiry and issuer with a maintained library (firebase/php-jwt), and never put personal data into the token.

Issue tokens

use Firebase\JWT\JWT;

add_action( 'rest_api_init', function (): void {
    register_rest_route( 'ha-auth/v1', '/token', array(
        'methods'             => 'POST',
        'permission_callback' => '__return_true', // public: this is the login
        'callback'            => 'ha_issue_token',
    ) );
} );

function ha_issue_token( WP_REST_Request $request ) {
    $user = wp_authenticate( (string) $request['username'], (string) $request['password'] );
    if ( is_wp_error( $user ) ) {
        return new WP_Error( 'ha_auth_failed', __( 'Invalid credentials.', 'textdomain' ), array( 'status' => 401 ) );
    }

    $now   = time();
    $token = JWT::encode( array(
        'iss' => home_url(),
        'sub' => $user->ID,
        'iat' => $now,
        'exp' => $now + 15 * MINUTE_IN_SECONDS,
    ), HA_JWT_SECRET, 'HS256' );

    $refresh = wp_generate_password( 64, false );
    update_user_meta( $user->ID, 'ha_refresh_' . wp_hash( $refresh ), $now + 30 * DAY_IN_SECONDS );

    return array( 'access_token' => $token, 'expires_in' => 900, 'refresh_token' => $refresh );
}

wp_authenticate() runs the normal login checks, including brute-force protections and two-factor plugins that hook into it. HA_JWT_SECRET is a long random value defined in wp-config.php, never in the plugin code. The payload holds only the user ID and times: a JWT is signed, not encrypted, and anyone can read its content. The refresh token is stored as a hash, so a database leak does not reveal usable tokens.

Accept tokens on REST requests

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

add_filter( 'determine_current_user', 'ha_jwt_user', 20 );
function ha_jwt_user( $user_id ) {
    if ( $user_id ) {
        return $user_id; // already logged in by cookie or another method
    }
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if ( ! preg_match( '/^Bearer\s+(\S+)$/', $header, $m ) ) {
        return $user_id;
    }
    try {
        $claims = JWT::decode( $m[1], new Key( HA_JWT_SECRET, 'HS256' ) );
    } catch ( Throwable $e ) {
        return $user_id; // invalid or expired: stay anonymous, the route decides
    }
    if ( ( $claims->iss ?? '' ) !== home_url() ) {
        return $user_id;
    }
    return (int) $claims->sub;
}

JWT::decode() checks the signature and exp, and passing the algorithm in the Key object prevents the “alg: none” and algorithm confusion attacks that hand-written JWT code is known for. The filter only sets the current user; each route’s permission_callback still checks capabilities. On Apache, the Authorization header is often stripped before PHP; SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 in .htaccess passes it through.

Refresh and revoke

A /token/refresh route accepts the refresh token, looks up ha_refresh_{hash}, issues a new pair and deletes the old meta entry (rotation). Logging out deletes the user’s refresh entries; changing the password should do the same, with a hook on after_password_reset and profile_update. Access tokens cannot be revoked before they expire, which is why they live only 15 minutes.

NOTE: For server-to-server integrations, Application Passwords are simpler and revocable per application in the user profile; JWT is worth the extra code for apps where users log in themselves. Custom endpoints and their permission checks: custom REST API endpoints. Limit the request rate of the token route like a login form: Nginx rate limiting.