Skip to content

Lesson 4 of 9 · 25m

Authentication and Authorization for PHP APIs

Choose the credential model deliberately, validate tokens correctly, and keep object-level authorization out of controllers' blind spots.

Most API breaches are not cryptographic wizardry. They are a missing object-level check: the user is logged in, the token is valid, and the endpoint happily returns someone else's invoice. Authentication answers 'who are you?' Authorization answers 'may you touch this object?' You need both, in that order, every time.

Pick the credential model for the client

  • First-party browser or mobile app: short-lived access tokens plus refresh rotation, or hardened cookies for browser-only apps.
  • Server-to-server integration: OAuth2 client credentials or signed API keys with strict secret storage.
  • Machine automation inside your own infrastructure: workload identity or mutual TLS where available.

API keys are not evil, but they are bearer secrets. If you issue them, store hashes server-side, scope them narrowly, record creation and last-use metadata, and support rotation without downtime.

Validate JWTs like a parser, not a fan

A JWT is only a signed claim set. Validate the signature, issuer, audience, expiry, and algorithm using a maintained library. Never trust the alg header blindly.

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

$claims = (array) JWT::decode($token, new Key($publicKey, 'RS256'));

if (($claims['iss'] ?? null) !== 'https://auth.sudosecurity.org') {
    throw new UnauthorizedException('bad issuer');
}
if (($claims['aud'] ?? null) !== 'billing-api') {
    throw new UnauthorizedException('bad audience');
}

Pin the accepted algorithms. none and unexpected symmetric/asymmetric confusion attacks are old tricks that still work wherever validation is sloppy.

Scopes are coarse; object checks are exact

A token with invoices:read does not mean every invoice is readable. It means the caller is allowed to attempt invoice reads. The final check happens against the object:

if (!$policy->canView($authenticatedUser, $invoice)) {
    throw new AccessDeniedHttpException();
}

Write policies or gates once and use them in controllers, GraphQL resolvers, queued jobs, and admin tools. If the rule only exists in one controller, another entry point will eventually bypass it.

Do not leak identity through errors

401 means no valid credentials. 403 means credentials are valid but insufficient. Do not return 403 with a message like invoice belongs to tenant 42 — that leaks internal tenancy. Also be deliberate about 404 versus 403; hiding existence is often safer, but consistency matters because timing and error differences can reveal information.

Field notes

  • Never accept tokens in query strings. They end up in logs, browser history, analytics, and referrers.
  • Rotate signing keys with overlap: publish the new public key before retiring the old one.
  • Rate-limit authentication failures separately. Otherwise attackers turn your login or token endpoint into an oracle.
  • Test horizontal access (user A reads user B's object) as carefully as unauthenticated access. It is the more common breach.

Was this lesson helpful?

Sign in to rate