Course API Development

Authentication & Tokens

Securing & Shipping Preview

Auth options

MethodUse forNotes
API keyServer-to-serverSimple, shared secret
Token / JWTApps with usersStateless, popular
OAuth 2.0Third-party appsFull standard
Session cookiesSame-site front-endBrowser-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.


Discussion