Session Authentication vs Token Authentication

Session Authentication vs Token Authentication

  1. In Session-based Authentication the Server does all the heavy lifting server-side. Broadly speaking a client authenticates with its credentials and receives a session_id (which can be stored in a cookie) and attaches this to every subsequent outgoing request. So this could be considered a "token" as it is the equivalent of a set of credentials. There is however nothing fancy about this session_id string. It is just an identifier and the server does everything else. It is stateful. It associates the identifier with a user account (e.g. in memory or in a database). It can restrict or limit this session to certain operations or a certain time period and can invalidate it if there are security concerns. More importantly it can do and change all of this on the fly. Furthermore it can log the user's every move on the website(s). Possible disadvantages are bad scale-ability (especially over more than one server farm) and extensive memory usage.

  2. In Token-based Authentication no session is persisted server-side (stateless). The initial steps are the same. Credentials are exchanged against a token which is then attached to every subsequent request (it can also be stored in a cookie). However for the purpose of decreasing memory usage, easy scale-ability and total flexibility (tokens can be exchanged with another client) a string with all the necessary information is issued (the token) which is checked after each request made by the client to the server. There are a number of ways to use/create tokens:

    1. Using a hash mechanism e.g. HMAC-SHA1

      token = user_id|expiry_date|HMAC(user_id|expiry_date, k)
      

      where user_id and expiry_date are sent in plaintext with the resulting hash attached (k is only know to the server).

    2. Encrypting the token symmetrically e.g. with AES

      token = AES(user_id|expiry_date, x)
      

      where x represents the en-/decryption key.

    3. Encrypting it asymmetrically e.g. with RSA

      token = RSA(user_id|expiry_date, private key)
      

Production systems are usually more complex than those two archetypes. Amazon for example uses both mechanisms on its website. Also hybrids can be used to issue tokens as described in 2 and also associate a user session with it for user tracking or possible revocation and still retain the client flexibility of classic tokens. Also OAuth 2.0 uses short-lived and specific bearer-tokens and longer-lived refresh tokens e.g. to get bearer-tokens.

Sources:

 

What really is the difference between session and token based authentication

A friend who is just getting into using Nodejs for backend development asked me to explain the difference between using session and jwt. So I thought I’d write this for any other person trying to understand what it means when you hear other developers talk about sessions and token based authentication.

Quick Introduction

Firstly, let’s talk about the HTTP (HyperText Transfer Protocol). From a quick Google search we get that:

HTTP is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.

From the above definition, we can tell that HTTP is what enables communication between a client (frontend) and a server (backend). HTTP is stateless so each request made is totally unaware of any action taken previously. Say for example we just logged into our twitter account and we navigate to our settings page, with the default HTTP behavior, we would be required to log back in again because the server has no idea that we just logged in but with session and token authentication we can tell the server that we are already logged in and we have should be granted access to that page.

What is session based authentication?

Session based authentication is one in which the user state is stored on the server’s memory. When using a session based auth system, the server creates and stores the session data in the server memory when the user logs in and then stores the session Id in a cookie on the user browser.
The session Id is then sent on subsequent requests to the server and the server compares it with the stored session data and proceeds to process the requested action.

What is token based authentication?

Token based authentication is one in which the user state is stored on the client. This has grown to be the preferred mode of authentication for RESTful APIs. In the token based authentication, the user data is encrypted into a JWT (JSON Web Token) with a secret and then sent back to the client.
The JWT is then stored on the client side mostly localStorage and sent as a header for every subsequent request. The server receives and validates the JWT before proceeding to send a response to the client.

headers:{
"Authorization": "Bearer ${JWT_TOKEN}"
}
  • A typical example of how the token is sent with the header to the server

When to use?

There really isn’t a preferred method for authentication, both methods can be used interchangeably or together to create a hybrid system. It all boils down to the developer and the use case.
However, it is worth noting that token based authentication scales better than that of a session because tokens are stored on the client side while session makes use of the server memory so it might become an issue when there is a large number of users using the system at once.

 

Session vs Token Based Authentication

HTTP is stateless. All the requests are stateless. However, there are situations where we would like our states to be remembered. For example, in a on-line shop, after we put bananas in a shopping cart, we don’t want our bananas to disappear when we go to another page to buy apples. ie. we want our purchase state to be remembered while we navigate through the on-line shop!

To overcome the stateless nature of HTTP requests, we could use either a session or a token.

Session Based Authentication

In the session based authentication, the server will create a session for the user after the user logs in. The session id is then stored on a cookie on the user’s browser. While the user stays logged in, the cookie would be sent along with every subsequent request. The server can then compare the session id stored on the cookie against the session information stored in the memory to verify user’s identity and sends response with the corresponding state!

 

 

Session Based Authentication flow

Token Based Authentication

Many web applications use JSON Web Token (JWT) instead of sessions for authentication. In the token based application, the server creates JWT with a secret and sends the JWT to the client. The client stores the JWT (usually in local storage) and includes JWT in the header with every request. The server would then validate the JWT with every request from the client and sends response.

 

 

Token Based Authentication flow

The biggest difference here is that the user’s state is not stored on the server, as the state is stored inside the token on the client side instead. Most of the modern web applications use JWT for authentication for reasons including scalability and mobile device authentication.

Node Modules for JWT

jsonwebtoken library can be used to created the JWT token on the server. Once the user is logged in, the client passes the JWT token back on the header.authorization.bearer attribute.

{
method: "GET",
headers:{
"Authorization": "Bearer ${JWT_TOKEN}"
}
}

Middleware, express-jwt, can be used to validate the JWT token by comparing the secret.

Scalability

Session based authentication: Because the sessions are stored in the server’s memory, scaling becomes an issue when there is a huge number of users using the system at once.

Token based authentication:There is no issue with scaling because token is stored on the client side.

Multiple Device

Session based authentication: Cookies normally work on a single domain or subdomains and they are normally disabled by browser if they work cross-domain (3rd party cookies). It poses issues when APIs are served from a different domain to mobile and web devices.

Token based authentication: There is no issue with cookies as the JWT is included in the request header.

Token Based Authentication using JWT is the more recommended method in modern web apps. One drawback with JWT is that the size of JWT is much bigger comparing with the session id stored in cookie because JWT contains more user information. Care must be taken to ensure only the necessary information is included in JWT and sensitive information should be omitted to prevent XSS security attacks.

 

 

 

posted @ 2020-06-19 18:49  ChuckLu  阅读(381)  评论(0编辑  收藏  举报