Skip to content
Skills Library
Programming · Tool integration

br-auth-middleware

/br-auth-middleware

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-argument redaction in custom verifier implementations.

Licence
MIT
Last repository change
20.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
2
Scripts
0
HTML comments
0
URLs in SKILL.md
2
Deprecation

No signals detected. Repository changed on 20.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

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-argument redaction in custom verifier implementations.

Original author description

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-argument redaction in custom verifier implementations.

How it works

  1. Choose the middleware
  2. JWT verification rules
  3. WordPress user mapping
  4. Native user scope in 1.1.1
  5. Shared identity
  6. Checks
  7. Sensitive arguments on the PHP 8.3 line
  8. References
Original SKILL.md headings · 85 lines, 668 words
SKILL.md preview
---
name: br-auth-middleware
description: 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-argument redaction in custom verifier implementations.
metadata:
  wp-skills-author: "Soczó Kristóf"
  wp-skills-contact: "mailto:lonsdale201@hotmail.com"
  wp-skills-plugin: "better-route"
  wp-skills-plugin-version-tested: "2.0.0"
  wp-skills-php-min: "8.3"
  wp-skills-last-updated: "2026-10-20"
---

# 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`.

```php
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

- Use `JwtAuthMiddleware` with `Hs256JwtVerifier` for first-party HS256 tokens.
- Use `BearerTokenAuthMiddleware` with `JwtBearerTokenVerifierAdapter` and `Rs256JwksJwtVerifier` for RS256/ES256 JWKS tokens. Follow `br-jwks-jwt-auth`.
- Use `BearerTokenAuthMiddleware` with a custom `BearerTokenVerifierInterface` for opaque or externally verified bearer tokens.
- Use `ApplicationPasswordAuthMiddleware` for server-to-server WordPress Application Password Basic authentication.
- Use `CookieNonceAuthMiddleware` for same-site browser requests with a logged-in WordPress cookie and `X-WP-Nonce`. Keep both `requireNonce` and `requireLoggedIn` enabled unless a separately reviewed design requires otherwise.

`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

- `exp` is required by default. Do not disable `requireExpiration` for normal production tokens.
- When `maxLifetimeSeconds` is set, both `iat` and `exp` are required and `exp - iat` must not exceed the limit.
- Set `expectedIssuer` and `expectedAudience` in production.
- Keep `maxTokenLength` bounded; the default is 8192 bytes.
- Required-scope wildcards are server-controlled. A token-supplied granted scope ending in `*` expands authority only when `allowGrantedScopeWildcards: true`; keep that opt-in off unless the issuer contract requires it.

## 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

- Verify mapped/unmapped identities, nested success/exception restoration, and the restored caller in response filters and embedding.
- Test missing, malformed, expired, future, wrong-issuer, wrong-audience, and over-lifetime tokens.
- Test every missing required scope and ensure a token-provided wildcard cannot widen authority unexpectedly.
- Test routes without `protectedByMiddleware()` fail closed.
- Never log bearer tokens, Basic credentials, cookies, nonces, or complete claims payloads.

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

- Official documentation: <https://lonsdale201.github.io/better-docs/docs/better-route/agents>
Files in this package (2)
  • SKILL.md 6 KB
  • agents/openai.yaml 1 KB

Versions

The database has no other skills named br-auth-middleware.

Database snapshot: 13.11.2026 · package version 180021b05c66 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100authentication
    Authentication and authorization for ASP.NET Core. Covers JWT bearer tokens, OpenID Connect, ASP.NET Identity, authorization policies, role and claim-based authorization, and API key authentication. Load this skill when implementing login, protecting endpoints, designing…
  • 100jwt-authentication
    Use when implementing stateless JWT authentication in Symfony with LexikJWTAuthenticationBundle — login endpoint, token issuance, refresh tokens, custom claims, and the JWT firewall. Use when the task mentions JWT, bearer token, access token, refresh token, or stateless API auth.
  • 91auth-rbac-scaffold
    Use when developer is implementing authentication, building login/logout flows, writing JWT validation, adding middleware, creating role-based access control, building permission systems, or asking how to protect routes. Also triggers on keywords: auth, bearer token, JWT,…
  • 100jwt-auth-setup
    Set up JWT authentication and authorization in ASP.NET Core. Use this skill whenever the user wants to add login/auth, issue or validate JWT tokens, set up bearer authentication, refresh tokens, role/policy-based authorization, claims, or asks "how do I secure my API / add JWT…
  • 100auth
    Choose and prepare authentication for Better Auth, Cloudflare Access, or another provider, and verify local readiness (config, env names, session or JWT validation, protected-route checks) without touching remote accounts. Use for /auth, login, sessions, Better Auth setup,…
  • 100auth-patterns
    This skill should be used when the user asks about "authentication in Next.js", "NextAuth", "Auth.js", "middleware auth", "protected routes", "session management", "JWT", "login flow", or needs guidance on implementing authentication and authorization in Next.js applications.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.