In this article, I will explain why we need authentication and compare the difference between session-based authentication v.s. token-based authentication.
How Authentication works
To start with, let’s first think about how authentication works.
- user login
- username/password pass on to the server
- server verified the information and grant the permission by sending back the authentication token
- once we receive the authentication token, we will use it in every of our user request
You might be wondering why we need to show our authentication token in every client request. This is because HTTP is stateless, which means HTTP will not remember the state of every request which means every request is unique and servers are not able to tell which client is sending the request.
To overcome this, we use one of the below technology to save the state:
- web storage(local storage, session storage)
- external file
Session-based authentication: Cookies
Server will create a session once user logs in and respond with a Set-Cookie in the header with session-id. Every following request then carries Cookie:session-id and uses it as a token to let server know who is sending the request. Once server receives the request, it can get the user detail by checking session-id. The session will be destroyed once user logs out.
In our browser, we save it in web storage after we received cookie detail. If you open dev tools in your chrome browser, you should be able to find your cookie detail as Application -> Storage -> cookie
Token-based authentication: JWT
For token-based authentication, we use JWT (JSON Web Tokens) as an authentication token.
After user logs in, server will create a JWT token and send it back to client. Every following request will have JWT in the header for server to identify who is sending the request. When user logs out, we will delete JWT from the client side(local storage)
In our browser, we save normally save it in Local Storage
JSON Web Tokens Structure
You can use this tool to decode your JWT token
JWT.IO - JSON Web Tokens Introduction
NEW: get the JWT Handbook for free and learn JWTs in depth! JSON Web Token (JWT) is an open standard ( RFC 7519) that…
Using Session Cookies Vs. JWT for Authentication | Hacker Noon
HTTP is a stateless protocol and is used to transmit data. It enables the communication between the client side and the…