Br auth middleware

From Lonsdale201/wp-agent-skills · View interactive version

Br auth middleware is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Configure Better Route authentication with JWT, custom bearer tokens, WordPress Application Passwords or cookie nonces. Use when protecting routes, mapping verified claims to WordPress users, enforcing scopes, consuming AuthContext, restoring native users after nested dispatch, or checking sensitive

How to use this skill

Skill file

Better Route authentication middleware

Select authentication by client type, attach it as middleware, and mark every raw route as middleware-protected. Better Route 1.1 denies every raw route by default, including GET and OPTIONS.

use BetterRoute\Middleware\Jwt\Hs256JwtVerifier;
use BetterRoute\Middleware\Jwt\JwtAuthMiddleware;

$auth = new JwtAuthMiddleware(
    verifier: new Hs256JwtVerifier(
        secret: MY_PLUGIN_JWT_SECRET,
        expectedIssuer: 'https://issuer.example',
        expectedAudience: 'my-api',
        maxLifetimeSeconds: 3600
    ),
    requiredScopes: ['orders:read']
);

$router->get('/orders/(?P<id>\d+)', $handler)
    ->middleware([$auth])
    ->protectedByMiddleware('bearerAuth');

Choose the middleware

protectedByMiddleware() tells the WordPress permission callback to let the request reach the middleware pipeline. It does not add authentication by itself: the authentication middleware must also be attached. The optional name describes the OpenAPI security scheme.

JWT verification rules

WordPress user mapping

WpClaimsUserMapper defaults to numeric user_id, uid, and wp_user_id claims. It deliberately does not interpret sub as a WordPress user ID and leaves email/login lookup disabled.

Prefer an issuer-scoped custom sub resolver. If email mapping is unavoidable, explicitly pass emailClaims and retain requireEmailVerified: true. Enable login-name mapping only for a fully controlled issuer. A mapped positive user ID becomes the native WordPress current user only during downstream execution (1.1.1).

Native user scope in 1.1.1

JWT, Bearer and Application Password middleware restore the previous WP user in finally, including exceptions. Nested calls unwind in reverse order. A verified JWT/Bearer identity without a positive WP mapping runs downstream as native user 0, never as an unrelated ambient user.

If you supply setCurrentUser, pair it with the appended optional getCurrentUser callback for the same identity store. The default getter calls get_current_user_id() or returns 0 outside WordPress. Previous constructor positions are unchanged.

WordPress permission callbacks run before middleware. Check middleware-established identity inside the downstream pipeline. Later rest_request_after_callbacks, rest_post_dispatch and _embed see the restored caller; use native WordPress request authentication when those phases need an authenticated user. Do not bypass permission checks or leave a global user set.

Shared identity

Successful built-in authentication writes a normalized identity into RequestContext::$attributes['auth'] with provider, userId, subject, and scopes. JWT/bearer claims and useful user fields are exposed through other context attributes. Ownership guards, rate-limit identity selection, and audit enrichment consume this shared contract; do not invent a parallel identity attribute.

Since 1.1.1, AuthContext::withIdentity() always replaces userId, user, claims and scopes, including null/empty values. Do not treat attribute presence alone as proof of a mapped user.

Checks

Source references: src/Middleware/Jwt/*, src/Middleware/Auth/*, src/Router/RouteBuilder.php.

Sensitive arguments on the PHP 8.3 line

Built-in credential, JWT/claim and scope helpers redact annotated arguments in their

own exception frames. Repeat #[\SensitiveParameter] on custom verifier/mapper

implementations and nested sensitive helpers; interface annotations do not propagate.

Messages, stored object state, request objects and onward native/custom callback

arguments remain outside that protection. Use br-php83-upgrade for the exact limits

and keep normal application logging redaction.

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.