How does authentication typically work for a RESTful API, and what is the difference between session based authentication and token based authentication using something like a JSON Web Token?
Short answer
Session based authentication relies on a server side session, typically identified through a cookie, which works well for traditional web applications but is less ideal for APIs consumed by mobile apps or separate frontend applications, while token based authentication, commonly…
Advertisement
AModel answer
Session based authentication relies on a server side session, typically identified through a cookie, which works well for traditional web applications but is less ideal for APIs consumed by mobile apps or separate frontend applications, while token based authentication, commonly using a JSON Web Token, issues a self contained, cryptographically signed token to the client after successful login, which the client then includes with every subsequent request, letting the server verify the token's validity without needing to maintain any server side session state at all.
$token = JWT::encode(['user_id' => $user->id, 'exp' => time() + 3600], $secretKey, 'HS256');
// Client includes token in Authorization header on future requests
// Authorization: Bearer <token>Real-world example
A mobile application authenticates against an API using a JSON Web Token, which is then included in the Authorization header of every subsequent request, letting the API remain completely stateless without needing to track individual user sessions on the server.
Likely follow-ups
- What information is typically encoded within a JSON Web Token's payload?
- How do you securely handle token expiration and refreshing an expired token?
Related topics