TechnicalMedium PHP & Laravel
What is the difference between session-based and token-based authentication?
Asked for Backend Developer, Full-Stack Developer
Why they ask this: Most Nepali startups build an API for a React or mobile frontend, so you must know which auth fits.
Answer
- Session-based: after login the server stores the session (in files, the database or Redis) and sends the browser a session cookie. Each request sends the cookie and the server looks up the session. This is stateful and works best for same-domain web apps. Protect it with CSRF tokens.
- Token-based: after login the server returns a token that the client sends in the
Authorization: Bearer <token>header. This suits mobile apps and third-party clients.- Opaque tokens (such as Laravel Sanctum personal access tokens) are stored in the database and are easy to revoke.
- JWTs are signed and self-contained, so the server does not need a lookup, but they are harder to revoke before they expire.
In Laravel, Sanctum handles both: cookie-based SPA authentication for your own frontend and API tokens for mobile apps. Never store tokens where scripts can read them (such as localStorage) if you can use an httpOnly cookie instead.
Can you explain this in your own words?