flow of traditional cookie-based authentication:
- User enters their login credentials.
- Server verifies the credentials are correct and creates a session which is then stored in a database.
- A cookie with the session ID is placed in the users browser.
- On subsequent requests, the session ID is verified against the database and if valid the request processed.
- Once a user logs out of the app, the session is destroyed both client-side and server-side.
token flow:
- User enters their login credentials.
- Server verifies the credentials are correct and returns a signed token.
- This token is stored client-side, most commonly in local storage - but can be stored in session storage or a cookie as well.
- Subsequent requests to the server include this token as an additional Authorization header or through one of the other methods mentioned above.
- The server decodes the JWT and if the token is valid processes the request.
- Once a user logs out, the token is destroyed client-side, no interaction with the server is necessary
- Tokens are stateless. The token is self-contained and contains all the information it needs for authentication. This is great for scalability as it frees your server from having to store session state.
- Tokens can be generated from anywhere. Token generation is decoupled from token verification allowing you the option to handle the signing of tokens on a separate server or even through a different company such us Auth0.
- Fine-grained access control. Within the token payload you can easily specify user roles and permissions as well as resources that the user can access.