Session vs Token Authentication

Sessions vs Tokens

HTTP and HTTPS are stateless, they don’t remember anything about the last request made (if there was one). So when you connect and login to a server, there needs to be a way for the server to remember that you are authenticated and authorized. Otherwise every single HTTP/S request to a protected route would require you to authenticate again. No one wants that! Sessions and tokens are two popular ways of doing this.

  • Session based: Stored server side in memory and client side in a cookie. Both are needed.
  • Token based: Stored client side only (usually), leaving the server stateless, a requirement for a REST API.

Tokens:

We already looked at tokens in the form of JSON Web Tokens (JWTs) in previous blog posts . With JWTs, the server would create one using a secret key and sent it to the client (sometimes inside a cookie) after the client successfully logged in (authenticated). The client would store this, and send it along to the server with each HTTP/S request. Usually sent inside a header or cookie. Stored in client memory, a cookie, or localStorage/sessionStorage. The server would not remember the client, and would use it’s secret key to decrypt the JWT and if it was valid, allow the request to go through. This keeps the server client API stateless, a requirement for a REST API. Technically you could use JWTs for sessions, but this is apparently a bad idea.

Sessions:

Session based authentication is a bit different, the user state is stored on the server side in memory. The server creates the session when the user logs is (authentication) and stores the session data in server memory, while giving the client a corresponding session ID inside a cookie. Each time the client makes an HTTP/S requests to that server it will send the cookie along with it, and if the route is protected the server will inspect the cookie to see if the user is authenticated and accept/deny the request based on this.

Which to pick?

Both are still extremely common. I personally think token based authentication is a better overall choice. Why? Because the server does not keep track of the state of which users are logged in, this allows you to easily scale up and increase the number of servers in real time for additional traffic. Each server would have the same secret key to decrypt tokens with, but would not need to be aware of which clients were logged in currently. With sessions, the server has to store all the clients session data. This makes scaling up to more servers in real time difficult since you now have to direct clients to the correct server that has stored their session data, or have all the servers communicate with each other, or have a central database server for storing session data. All it amounts to is more HTTP requests on your network for each request a client sends.

Also, tokens are stateless on the server side, which makes them a perfect fit for REST APIs.