Authentication & Tokens
Securing & Shipping
Preview
Auth options
| Method | Use for | Notes |
|---|---|---|
| API key | Server-to-server | Simple, shared secret |
| Token / JWT | Apps with users | Stateless, popular |
| OAuth 2.0 | Third-party apps | Full standard |
| Session cookies | Same-site front-end | Browser-based |
Bearer tokens
// Client sends:\nAuthorization: Bearer eyJhbGciOi...\n\n// Server checks:\n$auth = $_SERVER["HTTP_AUTHORIZATION"] ?? "";\nif (!str_starts_with($auth, "Bearer ")) {\n respond(["error" => "Missing token"], 401);\n}\n$token = substr($auth, 7);Issuing tokens
$payload = json_encode(["user_id" => $user["id"], "exp" => time() + 3600]);\n$token = base64_encode($payload) . "." . hash_hmac("sha256", $payload, $secret);Protecting a route
function requireUser() {\n $token = extractToken();\n $user = verifyToken($token);\n if (!$user) respond(["error" => "Unauthorized"], 401);\n return $user;\n}\n\n$user = requireUser();\nrespond(["message" => "Hello, {$user[\"name\"]}"]);Tip: For production, use a battle-tested JWT library rather than rolling your own crypto.
This is a free preview lesson
Enroll in the API Development to unlock every lesson, lesson PDF guides, quizzes and your certificate - and start creating your own pieces today.