My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Cookie vs Token authentication

Cookie vs Token authentication

Gaurav Kumar Dey's photo
Gaurav Kumar Dey
·Jun 14, 2021·

5 min read

What's authentication?

In computing, authentication is the process of verifying the identity of a person or device. A simple example is entering a username and password when you log in to a website. On login to the website with the correct login information lets the website know who you are and that you are actually accessing the website.

A cookie is a small piece of data created by a server and sent to your browser when you visit a website. Browsers often need to store and send it back to the server to tell that the request is coming from the same browser, to keep the user authenticated. We read the browser cookies as "key-value" pairs.

This authentication technique uses HTTP cookies to authenticate the client requests and maintain session information on the server over the stateless HTTP protocol.

1_Hg1gUTXN5E3Nrku0jWCRow.png

  • The client sends a login request with credentials to the backend server from his device.

  • The server then validates the credentials. If the credentials are correct login is successful, the web server will create a session in the database.

  • This session ID is stored in a session cookie on the user’s browser. While the user remains logged in, the cookie is sent with every subsequent request.

  • At each request, the server takes a look at the session cookie to read the session ID. If it matches the data stored in its memory, it sends a response back to the browser letting it know everything’s okay and ready to go.

  • During the logout operation, the server will make the cookie expire by deleting it from the database.

Token-based authentication

In token-based authentication, we store the user’s state on the client. This is achieved with JSON Web Token (JWT). It is a standard that defines a way of securely transmitting information between a client and a server as a JSON object.

The jwt.io website can be used to parse the JWT token information. You can use this website to experiment with JSON Web Tokens by decoding and encoding them.

A simple token looks like

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

The data after decoding looks like

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Workflow of the token-based authentication process

1_PDry-Wb8JRquwnikIbJOJQ.png

  • The user submits login credentials to the backend server from his device.

  • On receiving the request, the server verifies the credentials before generating an encrypted JWT with a secret key and sends it back to the client.

  • On the client-side, the browser stores the token locally using the local storage, session storage or cookie storage.

  • On future requests, the JWT is added to the authorization header prefixed by the bearer, and the server will validate its signature by decoding the token before proceeding to send a response. The content of the header would look like this:

    { headers: { Authorization: Bearer <token> } }
    
  • On the logout operation, the token on the client-side is destroyed without server interaction.

Similarities between JSON Web Tokens and Session Cookies

Before getting into the differences between the authentication techniques, it’s essential to first understand their main similarity. They can both be used to authenticate users.

  1. Both keep user data authenticated at each new request.
  2. Both of them are secure options to use.

That’s about where the similarities end. So, what are the main differences between JSON web tokens and session cookies?

Differences between JSON Web Tokens and Session Cookies

  1. Cryptographic Signatures: JSON web tokens have cryptographic signatures, and that’s not the case with session cookies.
  2. JSON is Stateless: JSON web tokens are stateless because tokens are stored client-side, rather than in the server’s memory. Authentication can occur locally instead of per request, where requests have to go through the server’s database.
  3. Scalability: As session cookies are stored in the server’s memory, it has the potential of using a lot more resources if the website or app sees a lot of traffic. Because JSON web tokens are stateless, they can potentially save on server resources in many cases. This also means that JSON web tokens tend to be a lot more scalable as a result.
  4. Authentication Across Multiple Locations: Session cookies only work across a single domain, or on its subdomains. If they try to go to a third party, browsers tend to disable them. But with JSON web tokens, you can authenticate a user across multiple locations including multiple domains, mobile devices, and APIs. This is because they’re stored locally in the request header.

Which to choose when?

Both approaches are not a silver bullet when protecting your system. Web Security is a myth, no system is perfectly hacker-proof but these techniques make your website much more secure than plain username and passwords from hackers.

Use cookie authentication when the user profile needs personalization. When we need user preferences such as themes, we would use a cookie session in the database small to medium websites that just need to log a user in and access a few details that are stored in your site’s database, session cookies are usually enough.

Use token authentication when you have an enterprise-level site and you need to handle a lot of requests, especially with third parties, or a lot of third parties, including APIs at a different domain, JSON web tokens are more suitable.

Conclusion

JSON web tokens and session cookies both offer secure user authentication, but they have key differences that make them suitable in varying situations. Hope you have learnt a lot. Stay tuned for more such articles. Please share and comment below your views on this topic.

Connect me on LinkedIn