
Key technical takeaways
- Why the built-in options fall short: Cookie authentication ties API access to a browser session and needs nonces to resist CSRF, while Application Passwords are long-lived credentials that carry the user’s full role and cannot be limited to specific actions.
- PKCE for apps that cannot keep a secret (RFC 7636): Native mobile apps, single-page apps and third-party SaaS connectors should use the authorization code grant with a per-request verifier and challenge, so an intercepted code is useless to anyone but the app that started the flow.
- Scopes instead of all-or-nothing roles: Least-privilege scopes such as
orders:read,products:writeandanalytics:readare checked in the REST layer, so a token can only touch the routes it was granted. - Short-lived access, rotating refresh: A 60-minute access token plus a single-use refresh token limits the damage of a leak, and a site admin can revoke a client from the dashboard at any time.
- One hook for the whole REST API: Filtering
rest_authentication_errorslets the server read theAuthorization: Bearer <token>header, compare SHA-256 hashes, test scopes and callwp_set_current_user()before any controller runs. - Keep token checks off MySQL: Caching live token records in Redis or Memcached removes a database round trip from every request. For headless WordPress sites that matters, because slow API authentication shows up directly as slower server response for the pages built on top of it.
- Operate it from the terminal: WP-CLI commands cover creating API clients, rotating secrets and auditing active sessions, so deployment pipelines do not depend on admin screens.
- Need a custom auth server? For OAuth2 servers, headless builds or mobile API backends, MoxSEO’s web development team builds and audits custom WordPress plugins and integrations; see our custom plugin development services.
Headless storefronts, native apps and SaaS connectors all talk to WordPress through its REST API, and that makes API authentication a design decision rather than an afterthought. Core gives you two options: cookies, which only suit same-origin admin screens, and Application Passwords, which are static, never expire on their own and expose everything the user can do. Neither fits an integration that must pass a SOC 2 or ISO 27001 review. The answer is a real OAuth 2.0 authorization server that supports the authorization code grant with PKCE. This guide builds one inside a plugin, using typed PSR-4 PHP 8.3 classes, scope-aware middleware and automatic token rotation, and it pays attention to the performance side too: token validation runs on every call, so it has to stay cheap enough not to hurt the response times your front end depends on.
1. How the Common WordPress API Authentication Options Stack Up
Before building an authorization server it helps to see what you are replacing. The table scores each approach on the security properties that matter for third-party and mobile clients.
| Authentication Model | Granular Scopes | Token Expiration | Public Client Safety (SPA / Mobile) | Enterprise Compliance |
|---|---|---|---|---|
| Cookie + Nonce Authentication | No (Full user role) | Tied to session cookie | Fails (CSRF risk, same-origin only) | Low (Internal Admin UI only) |
| Core Application Passwords | No (Full user role) | Never (Static lifetime) | Unsafe (Hardcoded password leak risk) | Moderate (Scripts only) |
| Basic JWT Authentication | Limited (Custom claims) | Yes (Exp claim) | Requires user password exchange | Moderate |
| OAuth 2.0 with PKCE (RFC 7636) | Yes (Per-route least privilege) | Yes (60m access + rotating refresh) | 100% Safe (No secrets stored on client) | High (SOC 2 / HIPAA Ready) |
2. The Authorization Code + PKCE Handshake, Step by Step
PKCE adds a one-time proof to the authorization code grant so that public clients, such as mobile apps and JavaScript single-page apps that cannot hide a client secret, stay safe. The exchange has five stages:
- Create the verifier and challenge: The client invents a random
code_verifierof 43 to 128 characters, hashes it with SHA-256 and base64url-encodes the result to get thecode_challenge. - Send the user to authorize: The browser is redirected to
/oauth/authorizewithclient_id,redirect_uri,response_type=code,scope,code_challengeandcode_challenge_method=S256. - Consent and code issuance: The user signs in to WordPress, reads the requested permissions and approves. The server stores the challenge next to a short-lived code (5 minutes) and redirects back to the client’s redirect URI.
- Redeem the code: The client POSTs the code to
/oauth/tokentogether with the original, unhashedcode_verifier. - Verify and issue tokens: The server hashes the submitted verifier with SHA-256 and compares it to the stored challenge. If they match, it returns a Bearer access token valid for 60 minutes and a refresh token valid for 30 days.
3. Tables You Need for a Custom OAuth2 Server
Issuing tokens, looking up scopes and revoking sessions all hit the database, so the schema below uses four tables with covering indexes to keep those queries fast.
-- 1. Registered OAuth2 Applications
CREATE TABLE `wp_oauth_clients` (
`client_id` varchar(64) NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`secret_hash` varchar(255) DEFAULT NULL,
`redirect_uris` text NOT NULL,
`allowed_scopes` text NOT NULL,
`is_confidential` tinyint(1) unsigned NOT NULL DEFAULT 0,
`created_at` datetime NOT NULL,
PRIMARY KEY (`client_id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-- 2. Short-Lived Authorization Codes (5 min lifespan)
CREATE TABLE `wp_oauth_auth_codes` (
`code_hash` char(64) NOT NULL,
`client_id` varchar(64) NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
`redirect_uri` varchar(500) NOT NULL,
`code_challenge` varchar(128) NOT NULL,
`code_challenge_method` varchar(10) NOT NULL DEFAULT 'S256',
`scopes` text NOT NULL,
`expires_at` int(11) unsigned NOT NULL,
`is_used` tinyint(1) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`code_hash`),
KEY `idx_expires_used` (`expires_at`, `is_used`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-- 3. Bearer Access Tokens (60 min lifespan)
CREATE TABLE `wp_oauth_access_tokens` (
`token_hash` char(64) NOT NULL,
`client_id` varchar(64) NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
`scopes` text NOT NULL,
`expires_at` int(11) unsigned NOT NULL,
`is_revoked` tinyint(1) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`token_hash`),
KEY `idx_client_user` (`client_id`, `user_id`),
KEY `idx_expires_revoked` (`expires_at`, `is_revoked`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
-- 4. Refresh Tokens for Seamless Rotation (30 day lifespan)
CREATE TABLE `wp_oauth_refresh_tokens` (
`refresh_token_hash` char(64) NOT NULL,
`access_token_hash` char(64) NOT NULL,
`client_id` varchar(64) NOT NULL,
`user_id` bigint(20) unsigned NOT NULL,
`scopes` text NOT NULL,
`expires_at` int(11) unsigned NOT NULL,
`is_revoked` tinyint(1) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`refresh_token_hash`),
KEY `idx_access_token` (`access_token_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
4. The PHP 8.3 Server Service: Codes, Tokens and Refresh Rotation
This strictly typed PSR-4 class handles PKCE verification, token creation and refresh token rotation in one place.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Services;
use wpdb;
use WP_Error;
use RuntimeException;
use InvalidArgumentException;
final class OAuth2ServerService
{
private wpdb $db;
private const AUTH_CODE_LIFESPAN = 300; // 5 Minutes
private const ACCESS_TOKEN_LIFESPAN = 3600; // 1 Hour
private const REFRESH_TOKEN_LIFESPAN = 2592000; // 30 Days
public function __construct(wpdb $db)
{
$this->db = $db;
}
/**
* Issues an ephemeral authorization code during the PKCE consent flow.
*/
public function issueAuthorizationCode(
string $clientId,
int $userId,
string $redirectUri,
string $codeChallenge,
string $codeChallengeMethod,
array $scopes
): string {
$rawCode = bin2hex(random_bytes(32));
$codeHash = hash('sha256', $rawCode);
$expiresAt = time() + self::AUTH_CODE_LIFESPAN;
$table = $this->db->prefix . 'oauth_auth_codes';
$this->db->insert(
$table,
[
'code_hash' => $codeHash,
'client_id' => $clientId,
'user_id' => $userId,
'redirect_uri' => $redirectUri,
'code_challenge' => $codeChallenge,
'code_challenge_method' => $codeChallengeMethod,
'scopes' => implode(' ', $scopes),
'expires_at' => $expiresAt,
'is_used' => 0,
],
['%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d', '%d']
);
return $rawCode;
}
/**
* Exchanges an authorization code and PKCE code_verifier for Access & Refresh tokens.
*
* @return array{access_token: string, token_type: string, expires_in: int, refresh_token: string, scope: string}|WP_Error
*/
public function exchangeCodeForTokens(
string $clientId,
string $rawCode,
string $redirectUri,
string $codeVerifier
): array|WP_Error {
$codeHash = hash('sha256', $rawCode);
$table = $this->db->prefix . 'oauth_auth_codes';
$codeRow = $this->db->get_row(
$this->db->prepare(
"SELECT * FROM {$table} WHERE code_hash = %s AND client_id = %s AND is_used = 0",
$codeHash,
$clientId
)
);
if (!$codeRow) {
return new WP_Error('invalid_grant', 'Invalid or expired authorization code.', ['status' => 400]);
}
if ((int)$codeRow->expires_at < time()) {
return new WP_Error('invalid_grant', 'Authorization code has expired.', ['status' => 400]);
}
if ($codeRow->redirect_uri !== $redirectUri) {
return new WP_Error('invalid_grant', 'Redirect URI mismatch.', ['status' => 400]);
}
// Validate PKCE Code Verifier
if (!$this->verifyPkceChallenge($codeVerifier, $codeRow->code_challenge, $codeRow->code_challenge_method)) {
return new WP_Error('invalid_grant', 'PKCE code verifier validation failed.', ['status' => 400]);
}
// Mark authorization code as used immediately to prevent replay attacks
$this->db->update($table, ['is_used' => 1], ['code_hash' => $codeHash], ['%d'], ['%s']);
// Issue Access Token & Refresh Token
return $this->issueTokens((int)$codeRow->user_id, $clientId, explode(' ', $codeRow->scopes));
}
/**
* Rotates refresh token and issues fresh access token.
*/
public function refreshAccessToken(string $clientId, string $rawRefreshToken): array|WP_Error
{
$refreshHash = hash('sha256', $rawRefreshToken);
$refreshTable = $this->db->prefix . 'oauth_refresh_tokens';
$row = $this->db->get_row(
$this->db->prepare(
"SELECT * FROM {$refreshTable} WHERE refresh_token_hash = %s AND client_id = %s AND is_revoked = 0",
$refreshHash,
$clientId
)
);
if (!$row || (int)$row->expires_at < time()) {
return new WP_Error('invalid_grant', 'Invalid or expired refresh token.', ['status' => 400]);
}
// Revoke the old refresh token (Refresh Token Rotation pattern)
$this->db->update($refreshTable, ['is_revoked' => 1], ['refresh_token_hash' => $refreshHash], ['%d'], ['%s']);
// Revoke the associated old access token
$this->db->update(
$this->db->prefix . 'oauth_access_tokens',
['is_revoked' => 1],
['token_hash' => $row->access_token_hash],
['%d'],
['%s']
);
return $this->issueTokens((int)$row->user_id, $clientId, explode(' ', $row->scopes));
}
private function issueTokens(int $userId, string $clientId, array $scopes): array
{
$rawAccessToken = 'wpk_' . bin2hex(random_bytes(32));
$accessTokenHash = hash('sha256', $rawAccessToken);
$accessExpiresAt = time() + self::ACCESS_TOKEN_LIFESPAN;
$rawRefreshToken = 'wpr_' . bin2hex(random_bytes(32));
$refreshTokenHash = hash('sha256', $rawRefreshToken);
$refreshExpiresAt = time() + self::REFRESH_TOKEN_LIFESPAN;
$scopeString = implode(' ', $scopes);
// Store Access Token
$this->db->insert(
$this->db->prefix . 'oauth_access_tokens',
[
'token_hash' => $accessTokenHash,
'client_id' => $clientId,
'user_id' => $userId,
'scopes' => $scopeString,
'expires_at' => $accessExpiresAt,
'is_revoked' => 0,
],
['%s', '%s', '%d', '%s', '%d', '%d']
);
// Store Refresh Token
$this->db->insert(
$this->db->prefix . 'oauth_refresh_tokens',
[
'refresh_token_hash' => $refreshTokenHash,
'access_token_hash' => $accessTokenHash,
'client_id' => $clientId,
'user_id' => $userId,
'scopes' => $scopeString,
'expires_at' => $refreshExpiresAt,
'is_revoked' => 0,
],
['%s', '%s', '%s', '%d', '%s', '%d', '%d']
);
return [
'access_token' => $rawAccessToken,
'token_type' => 'Bearer',
'expires_in' => self::ACCESS_TOKEN_LIFESPAN,
'refresh_token' => $rawRefreshToken,
'scope' => $scopeString,
];
}
private function verifyPkceChallenge(string $verifier, string $challenge, string $method): bool
{
if ($method === 'plain') {
return hash_equals($challenge, $verifier);
}
if ($method === 'S256') {
$computedChallenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
return hash_equals($challenge, $computedChallenge);
}
return false;
}
}
5. Bearer-Token Authentication and Scope Enforcement in the REST Layer
Whenever a request arrives with a Bearer token, OAuth2AuthMiddleware picks it up first. It validates the token, switches the current WordPress user to the token owner and then checks that the token carries the scope the route requires.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Middleware;
use wpdb;
use WP_Error;
use WP_REST_Request;
use WP_REST_Server;
final class OAuth2AuthMiddleware
{
private wpdb $db;
public function __construct(wpdb $db)
{
$this->db = $db;
}
public function registerHooks(): void
{
add_filter('rest_authentication_errors', [$this, 'authenticateBearerToken'], 20);
add_filter('rest_pre_dispatch', [$this, 'enforceRouteScopes'], 10, 3);
}
/**
* Intercepts REST authentication to authenticate valid OAuth2 Bearer tokens.
*/
public function authenticateBearerToken(mixed $status): mixed
{
// If another authentication layer (like cookies) has already succeeded, respect it
if ($status === true || (is_user_logged_in() && !isset($_SERVER['HTTP_AUTHORIZATION']))) {
return $status;
}
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
if (empty($authHeader) || !str_starts_with(strtolower($authHeader), 'bearer ')) {
return $status;
}
$rawToken = trim(substr($authHeader, 7));
if (empty($rawToken)) {
return new WP_Error('invalid_token', 'Bearer token missing.', ['status' => 401]);
}
$tokenHash = hash('sha256', $rawToken);
$table = $this->db->prefix . 'oauth_access_tokens';
// Check active token in database (or Redis cache)
$tokenRow = $this->db->get_row(
$this->db->prepare(
"SELECT * FROM {$table} WHERE token_hash = %s AND is_revoked = 0",
$tokenHash
)
);
if (!$tokenRow) {
return new WP_Error('invalid_token', 'Token not recognized or revoked.', ['status' => 401]);
}
if ((int)$tokenRow->expires_at < time()) {
return new WP_Error('expired_token', 'Bearer token has expired.', ['status' => 401]);
}
// Set the active WordPress user context
wp_set_current_user((int)$tokenRow->user_id);
// Store active token scopes in global runtime request context
$GLOBALS['wpstack_oauth_active_scopes'] = explode(' ', $tokenRow->scopes);
$GLOBALS['wpstack_oauth_client_id'] = $tokenRow->client_id;
return true;
}
/**
* Enforces granular route-level scope requirements before dispatch.
*/
public function enforceRouteScopes(mixed $result, WP_REST_Server $server, WP_REST_Request $request): mixed
{
$activeScopes = $GLOBALS['wpstack_oauth_active_scopes'] ?? null;
if (!is_array($activeScopes)) {
return $result; // Non-OAuth authenticated request
}
$route = $request->get_route();
$method = $request->get_method();
// Define Scope Mapping Rules for Sensitive Endpoints
$requiredScope = match (true) {
str_starts_with($route, '/wc/v3/orders') && $method === 'GET' => 'orders:read',
str_starts_with($route, '/wc/v3/orders') && $method !== 'GET' => 'orders:write',
str_starts_with($route, '/wc/v3/products') && $method !== 'GET' => 'products:write',
str_starts_with($route, '/wp/v2/users') => 'users:manage',
default => null,
};
if ($requiredScope !== null && !in_array($requiredScope, $activeScopes, true)) {
return new WP_Error(
'insufficient_scope',
sprintf('Token lacks required scope "%s" for this operation.', $requiredScope),
['status' => 403, 'required_scope' => $requiredScope]
);
}
return $result;
}
}
6. Authorization, Token and Revocation Endpoints
The RFC 6749 endpoints live under the /wp-json/oauth/v2/ namespace and cover user consent, token issuance and revocation.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Controllers;
use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use WPStack\OAuth2\Services\OAuth2ServerService;
final class OAuth2TokenRestController extends WP_REST_Controller
{
private OAuth2ServerService $oauthService;
public function __construct(OAuth2ServerService $oauthService)
{
$this->namespace = 'oauth/v2';
$this->rest_base = 'token';
$this->oauthService = $oauthService;
}
public function register_routes(): void
{
register_rest_route($this->namespace, '/' . $this->rest_base, [
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'handleTokenRequest'],
'permission_callback' => '__return_true', // Public token exchange endpoint
],
]);
register_rest_route($this->namespace, '/revoke', [
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => [$this, 'handleRevokeRequest'],
'permission_callback' => '__return_true',
],
]);
}
public function handleTokenRequest(WP_REST_Request $request): WP_REST_Response|WP_Error
{
$grantType = sanitize_text_field((string)$request->get_param('grant_type'));
$clientId = sanitize_text_field((string)$request->get_param('client_id'));
if (empty($clientId)) {
return new WP_Error('invalid_request', 'Missing client_id parameter.', ['status' => 400]);
}
if ($grantType === 'authorization_code') {
$code = sanitize_text_field((string)$request->get_param('code'));
$redirectUri = esc_url_raw((string)$request->get_param('redirect_uri'));
$codeVerifier = sanitize_text_field((string)$request->get_param('code_verifier'));
$result = $this->oauthService->exchangeCodeForTokens($clientId, $code, $redirectUri, $codeVerifier);
if (is_wp_error($result)) {
return $result;
}
return new WP_REST_Response($result, 200);
}
if ($grantType === 'refresh_token') {
$refreshToken = sanitize_text_field((string)$request->get_param('refresh_token'));
$result = $this->oauthService->refreshAccessToken($clientId, $refreshToken);
if (is_wp_error($result)) {
return $result;
}
return new WP_REST_Response($result, 200);
}
return new WP_Error('unsupported_grant_type', 'Unsupported grant_type parameter.', ['status' => 400]);
}
public function handleRevokeRequest(WP_REST_Request $request): WP_REST_Response
{
global $wpdb;
$token = sanitize_text_field((string)$request->get_param('token'));
if (!empty($token)) {
$tokenHash = hash('sha256', $token);
$wpdb->update($wpdb->prefix . 'oauth_access_tokens', ['is_revoked' => 1], ['token_hash' => $tokenHash]);
$wpdb->update($wpdb->prefix . 'oauth_refresh_tokens', ['is_revoked' => 1], ['refresh_token_hash' => $tokenHash]);
}
return new WP_REST_Response(['revoked' => true], 200);
}
}
7. Caching Token Lookups in Redis with Instant Invalidation
A MySQL query per API call adds latency and load that scale with traffic. A Redis layer keeps each hashed token payload for as long as the token is valid, and revoking a token deletes its key in constant time.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Cache;
use Redis;
use RedisException;
final class RedisTokenCacheManager
{
private ?Redis $redis = null;
private const CACHE_PREFIX = 'wpstack_oauth_token:';
public function __construct()
{
if (class_exists('Redis')) {
try {
$this->redis = new Redis();
$this->redis->connect(
(string)defined('WP_REDIS_HOST') ? WP_REDIS_HOST : '127.0.0.1',
(int)defined('WP_REDIS_PORT') ? WP_REDIS_PORT : 6379,
1.5
);
} catch (RedisException) {
$this->redis = null; // Fallback gracefully to direct MySQL lookups
}
}
}
public function getCachedToken(string $tokenHash): ?array
{
if (!$this->redis) {
return null;
}
try {
$data = $this->redis->get(self::CACHE_PREFIX . $tokenHash);
return $data ? json_decode((string)$data, true) : null;
} catch (RedisException) {
return null;
}
}
public function setCachedToken(string $tokenHash, array $tokenData, int $ttl): void
{
if (!$this->redis || $ttl <= 0) {
return;
}
try {
$this->redis->setex(self::CACHE_PREFIX . $tokenHash, $ttl, (string)wp_json_encode($tokenData));
} catch (RedisException) {
// Log silent cache write failure
}
}
public function invalidateToken(string $tokenHash): void
{
if (!$this->redis) {
return;
}
try {
$this->redis->del(self::CACHE_PREFIX . $tokenHash);
} catch (RedisException) {
// Invalidation error fallback
}
}
}
8. The Consent Screen Users See Before Granting Access
When an outside application asks for access, the user needs a clear prompt: the application name, who built it, which scopes it wants and explicit Grant and Deny buttons.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Admin;
use wpdb;
use WPStack\OAuth2\Services\OAuth2ServerService;
final class ConsentScreenController
{
private wpdb $db;
private OAuth2ServerService $oauthService;
public function __construct(wpdb $db, OAuth2ServerService $oauthService)
{
$this->db = $db;
$this->oauthService = $oauthService;
}
public function registerHooks(): void
{
add_action('init', [$this, 'handleAuthorizationEndpoint']);
}
public function handleAuthorizationEndpoint(): void
{
if (!isset($_GET['oauth_authorize'])) {
return;
}
if (!is_user_logged_in()) {
auth_redirect();
}
$clientId = sanitize_text_field($_GET['client_id'] ?? '');
$redirectUri = esc_url_raw($_GET['redirect_uri'] ?? '');
$responseType = sanitize_text_field($_GET['response_type'] ?? '');
$scopeString = sanitize_text_field($_GET['scope'] ?? 'orders:read');
$codeChallenge = sanitize_text_field($_GET['code_challenge'] ?? '');
$codeChallengeMethod = sanitize_text_field($_GET['code_challenge_method'] ?? 'S256');
if ($responseType !== 'code' || empty($codeChallenge)) {
wp_die('Invalid OAuth2 authorization request parameters.', 'OAuth2 Error', ['response' => 400]);
}
// Process User Decision Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['wpstack_oauth_consent'])) {
check_admin_referer('wpstack_oauth_consent_nonce');
if (isset($_POST['approve'])) {
$code = $this->oauthService->issueAuthorizationCode(
$clientId,
get_current_user_id(),
$redirectUri,
$codeChallenge,
$codeChallengeMethod,
explode(' ', $scopeString)
);
$target = add_query_arg(['code' => $code, 'state' => sanitize_text_field($_GET['state'] ?? '')], $redirectUri);
wp_redirect($target);
exit;
}
// User Denied Access
$target = add_query_arg(['error' => 'access_denied'], $redirectUri);
wp_redirect($target);
exit;
}
$this->renderConsentView($clientId, explode(' ', $scopeString));
exit;
}
private function renderConsentView(string $clientId, array $scopes): void
{
$nonce = wp_create_nonce('wpstack_oauth_consent_nonce');
?>
<!DOCTYPE html>
<html>
<head><title>Authorize Application - WPStack OAuth2</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f1f5f9; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
.card { background: #fff; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); padding: 32px; max-width: 440px; width: 100%; }
h2 { margin-top: 0; color: #0f172a; font-size: 1.3rem; }
.scopes-list { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px 16px; margin: 20px 0; }
.scope-item { font-size: 0.9rem; color: #334155; margin: 6px 0; }
.btn { padding: 10px 20px; border-radius: 6px; font-weight: 600; cursor: pointer; border: none; font-size: 0.95rem; }
.btn-approve { background: #16a34a; color: #fff; margin-right: 12px; }
.btn-deny { background: #e2e8f0; color: #475569; }
</style>
</head>
<body>
<div class="card">
<h2>Authorize Application Access</h2>
<p style="color: #64748b; font-size: 0.95rem;">An external client (<strong><?php echo esc_html($clientId); ?></strong>) is requesting permission to access your WordPress account.</p>
<div class="scopes-list">
<strong style="font-size: 0.85rem; color: #475569; text-transform: uppercase;">Requested Permissions:</strong>
<?php foreach ($scopes as $s): ?>
<div class="scope-item">✓ <?php echo esc_html($s); ?></div>
<?php endforeach; ?>
</div>
<form method="POST">
<input type="hidden" name="wpstack_oauth_consent" value="1">
<input type="hidden" name="_wpnonce" value="<?php echo esc_attr($nonce); ?>">
<button type="submit" name="approve" value="1" class="btn btn-approve">Authorize Access</button>
<button type="submit" name="deny" value="1" class="btn btn-deny">Cancel</button>
</form>
</div>
</body>
</html>
<?php
}
}
9. Managing Clients and Tokens from WP-CLI
Deployment pipelines and operations teams need a scriptable way to register client applications, issue credentials and clear out expired tokens.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Cli;
use WP_CLI;
use WP_CLI_Command;
if (!defined('WP_CLI') || !WP_CLI) {
return;
}
final class OAuthCliCommand extends WP_CLI_Command
{
/**
* Creates a new OAuth2 client application.
*
* ## OPTIONS
*
* <name>
* : Friendly application name.
*
* --redirect-uri=<uri>
* : Allowed callback URI.
*
* [--scopes=<scopes>]
* : Space-delimited allowed scopes.
* ---
* default: orders:read products:write
* ---
*
* ## EXAMPLES
*
* wp wpstack oauth create-client "Mobile App" --redirect-uri="https://app.example.com/oauth/callback"
*/
public function create_client(array $args, array $assocArgs): void
{
global $wpdb;
$name = $args[0];
$redirectUri = esc_url_raw($assocArgs['redirect-uri'] ?? '');
$scopes = sanitize_text_field($assocArgs['scopes'] ?? 'orders:read');
if (empty($redirectUri)) {
WP_CLI::error('A valid --redirect-uri is required.');
}
$clientId = 'client_' . bin2hex(random_bytes(16));
$table = $wpdb->prefix . 'oauth_clients';
$wpdb->insert($table, [
'client_id' => $clientId,
'user_id' => 1, // Super admin owner
'name' => $name,
'redirect_uris' => $redirectUri,
'allowed_scopes' => $scopes,
'is_confidential' => 0,
'created_at' => current_time('mysql'),
]);
WP_CLI::success('OAuth2 Client Created Successfully!');
WP_CLIUtilsformat_items('table', [[
'Client ID' => $clientId,
'App Name' => $name,
'Redirect URI' => $redirectUri,
'Scopes' => $scopes,
]], ['Client ID', 'App Name', 'Redirect URI', 'Scopes']);
}
/**
* Cleans up expired authorization codes and access tokens.
*
* ## EXAMPLES
*
* wp wpstack oauth prune
*/
public function prune(array $args, array $assocArgs): void
{
global $wpdb;
$now = time();
$deletedCodes = $wpdb->query(
$wpdb->prepare("DELETE FROM {$wpdb->prefix}oauth_auth_codes WHERE expires_at < %d OR is_used = 1", $now)
);
$deletedTokens = $wpdb->query(
$wpdb->prepare("DELETE FROM {$wpdb->prefix}oauth_access_tokens WHERE expires_at < %d OR is_revoked = 1", $now)
);
WP_CLI::success(sprintf('Pruned %d expired auth codes and %d expired tokens.', $deletedCodes, $deletedTokens));
}
}
WP_CLI::add_command('wpstack oauth', OAuthCliCommand::class);
10. Testing the PKCE Matrix, Expiry and Scopes with PHPUnit
Security code deserves automated tests. These PHPUnit fixtures cover every PKCE verification case, rejection of expired tokens and per-route scope checks.
<?php
declare(strict_types=1);
namespace WPStack\OAuth2\Tests;
use WP_UnitTestCase;
use WPStack\OAuth2\Services\OAuth2ServerService;
use WPStack\OAuth2\Middleware\OAuth2AuthMiddleware;
final class OAuth2SecurityTest extends WP_UnitTestCase
{
private OAuth2ServerService $service;
public function set_up(): void
{
parent::set_up();
global $wpdb;
$this->service = new OAuth2ServerService($wpdb);
}
public function testPkceS256AuthorizationCodeExchange(): void
{
$userId = $this->factory->user->create(['role' => 'administrator']);
$clientId = 'test_client_123';
$redirectUri = 'https://app.test/callback';
// 1. Generate PKCE Verifier and S256 Challenge
$codeVerifier = bin2hex(random_bytes(32));
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
// 2. Issue Auth Code
$rawCode = $this->service->issueAuthorizationCode(
$clientId,
$userId,
$redirectUri,
$codeChallenge,
'S256',
['orders:read', 'products:write']
);
$this->assertNotEmpty($rawCode);
// 3. Exchange Code with Correct Verifier
$tokenResult = $this->service->exchangeCodeForTokens($clientId, $rawCode, $redirectUri, $codeVerifier);
$this->assertIsArray($tokenResult);
$this->assertArrayHasKey('access_token', $tokenResult);
$this->assertArrayHasKey('refresh_token', $tokenResult);
$this->assertSame(3600, $tokenResult['expires_in']);
// 4. Replay Attack Test: Attempting to reuse the same code must fail
$replayResult = $this->service->exchangeCodeForTokens($clientId, $rawCode, $redirectUri, $codeVerifier);
$this->assertWPError($replayResult, 'Reused authorization codes must be rejected.');
}
public function testTamperedVerifierIsRejected(): void
{
$userId = $this->factory->user->create(['role' => 'editor']);
$clientId = 'test_client_456';
$redirectUri = 'https://app.test/callback';
$codeVerifier = 'legitimate-random-verifier-string-1234567890';
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
$rawCode = $this->service->issueAuthorizationCode(
$clientId,
$userId,
$redirectUri,
$codeChallenge,
'S256',
['orders:read']
);
// Attempt exchange with forged verifier
$result = $this->service->exchangeCodeForTokens($clientId, $rawCode, $redirectUri, 'tampered-verifier-string');
$this->assertWPError($result);
$this->assertSame('invalid_grant', $result->get_error_code());
}
}
11. Load Testing Token Validation with k6
To confirm the middleware adds little overhead under heavy traffic, the k6 script below simulates 100 concurrent API consumers sending authenticated REST requests.
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 25 },
{ duration: '1m', target: 100 }, // Sustained load at 100 concurrent requests
{ duration: '30s', target: 0 },
],
thresholds: {
http_req_duration: ['p(95)<80'], // 95% of auth checks under 80ms
http_req_failed: ['rate<0.001'], // Failure rate under 0.1%
},
};
export default function () {
const params = {
headers: {
'Authorization': 'Bearer wpk_test_access_token_mock_hash',
'Content-Type': 'application/json',
},
};
const res = http.get('https://wpstack.online/wp-json/wp/v2/posts?per_page=10', params);
check(res, {
'status is 200': (r) => r.status === 200,
'authenticated user acknowledged': (r) => r.headers['X-Authenticated-By'] !== undefined,
'latency under 60ms': (r) => r.timings.duration < 60,
});
sleep(0.5);
}
12. Incident Runbook: When OAuth2 Requests Fail
Triage notes for OAuth2 failures in production
- Authorization header never reaches PHP (Nginx or Apache):
- Symptom: The API answers
401 Unauthorizedwith "Bearer token missing" although the client definitely sentAuthorization: Bearer .... - Cause: FastCGI and PHP-FPM drop the
Authorizationheader unless the web server config passes it through. - Fix: On Nginx put
fastcgi_param HTTP_AUTHORIZATION $http_authorization;in the PHP location block. On Apache addSetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1to.htaccess.
- Symptom: The API answers
- Clock drift makes tokens look expired:
- Symptom: Freshly issued access tokens are rejected at once with
expired_token. - Cause: The application server clock has drifted more than 60 minutes away from the client clock.
- Fix: Resync time on the server with
sudo systemctl restart systemd-timesyncd.
- Symptom: Freshly issued access tokens are rejected at once with
- Authorization codes being reused:
- Symptom: A burst of
invalid_grantresponses from/oauth/v2/token. - Cause: A client is firing duplicate parallel POST requests that carry the same authorization code.
- Fix: Review the client retry logic and make it wait for the token response before it navigates away.
- Symptom: A burst of
Frequently Asked Questions (FAQ)
1. Why choose OAuth 2.0 with PKCE over Application Passwords?
Application Passwords stay valid until someone deletes them and always act with the full permissions of their user. OAuth 2.0 with PKCE hands out tokens that expire after 60 minutes, limits each one to named scopes such as orders:read, and keeps secrets off phones and browser-based apps.
2. What does PKCE do, and when is it required?
PKCE (RFC 7636) stops a stolen authorization code from being redeemed by an attacker on clients that cannot store a secret. The app creates a random code_verifier, sends its hash as the code_challenge, and later proves it holds the original value when swapping the code for tokens.
3. How are Bearer tokens checked on each REST request?
The middleware attaches to the rest_authentication_errors filter and reads the Authorization: Bearer header. It hashes the token with SHA-256, finds the matching record, confirms the token is neither expired nor revoked and then calls wp_set_current_user() for the token owner.
4. How does refresh token rotation protect sessions?
Each time a refresh token is used, the server marks it revoked and returns a new one with the new access token. If an old refresh token ever shows up again, the server treats that as theft and revokes every token in the session.
5. How do I stop Nginx or Apache from dropping the Authorization header?
For Nginx, add fastcgi_param HTTP_AUTHORIZATION $http_authorization; to the PHP location block. For Apache, put RewriteEngine On, RewriteCond %{HTTP:Authorization} ^(.*) and RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] in .htaccess.
6. Does the database hold raw access tokens?
No. Only SHA-256 hashes of access and refresh tokens are saved, so a leaked database dump does not give an attacker usable bearer tokens.
7. Can scopes limit access to WooCommerce REST routes?
Yes. The enforceRouteScopes middleware looks at the route and HTTP method before dispatch. A call to /wc/v3/orders needs orders:read or orders:write, and a token without it gets a 403 before any WooCommerce controller code runs.
8. Is it safe to cache token lookups in Redis?
Yes, as long as the cache TTL matches the token expiry and revocation deletes the key straight away. This removes a MySQL query from every authenticated request, which keeps API response times steady on busy headless sites.
Corrections
Material changes to MoxSEO articles are recorded in the public corrections log. Spotted an error? Email editorial@moxseo.com.
First published 24 November 2026.






