Application development generally requires authentication, and the stability of the authentication mechanism becomes critical for all applications. The choice of which authentication method to use can be measured depending on the project and team, and before you make that decision, you need to understand two common forms of WEB authentication: cookie-based authentication and token-based authentication.

Cookie-based authentication

Authentication is the process of exchanging user credentials for a unique identity.

In cookie-based authentication, this unique identifier (Cookie) is created on the server side and sent to the browser.

When logging into a Web application, the browser will receive a Cookie from its application’s server, which the browser will store and send along with each subsequent request to verify that the request came from the same user.

To better understand how cookies work, break the process down into five parts.

Cookie workflow

1. Use credentials to log in to the application

2. The server validates the credentials and creates a session

After the server authenticates the credentials successfully, create a session that can be stored in memory or in the database. For better scalability, it is recommended to store it in the database. If it is stored in memory, session problems may occur in load balancing or multi-server deployment scenarios.

3. The server responds to the browser by including the cookie in the set-cookie header

This cookie is sent through a name-value pair and contains a unique ID to identify the user.

In addition, cookies can contain details such as expiration date, scope, and expiration time. An example response with multiple set-cookie headers looks like this:

HTTP/2.0 200 OK Content-type: text/ HTML set-cookie: <cookie-name>=<cookie-value> set-cookie: <cookie-name>=<cookie-value>; Expires=<date> Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number> Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain> Set-Cookie: <cookie-name>=<cookie-value>; Path=<path> Set-Cookie: <cookie-name>=<cookie-value>; Secure Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly [page content]Copy the code
4. The browser stores the Cookie in the storage and sends it together with subsequent requests

When the server receives a request with a Cookie, it compares the session ID in the Cookie to the session in the database to validate the user.

You can use browser development tools to find all cookies saved in the browser in the Cookie store under the application section.

5. When a user logs out, the server deletes the session from the database

Once the user logs out, the server will expire the Cookie by clearing the database session, and the browser will delete it from the Cookie store.

Cookie features and advantages and disadvantages

With a brief overview of how cookies work, let’s take a look at their features and pros and cons.

This is a fully automated process

If you use cookies for authentication, you don’t need to explicitly develop anything to request the addition of cookies.

Cookies are handled by the browser, which automatically adds cookies to all requests.

Although this automated process makes development easier, there are some drawbacks. For example, some requests do not require any authentication, but with this approach, cookies will also be sent on each request.

In addition, CSRF attackers can use this mechanism to trick browsers into sending requests with cookies to bogus websites.

Security measures

By default, cookie-based authentication has no effective protection against attacks, and they are mainly vulnerable to cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.

However, Cookie headers can be explicitly modified to protect them from such attacks.

For example, using the HttpOnly attribute when setting Cookie headers can easily protect cookies from XSS attacks.

Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly
Copy the code

In addition, you can use the SameSite attribute in the Cookie header to effectively protect against CSRF attacks.

Set-Cookie: <cookie-name>=<cookie-value>; SameSite=Lax
Copy the code

The SameSite property has three values available:

  • SameSite=Lex: will ensure that browsers do not send on cross-site requestsCookieThis is the default behavior of cookies if the SameSite property is not defined.
  • SameSite=Strict: will ensure that the browser only sends requests for the same siteCookie.
  • SameSite=NoteWill allow sending through cross-site and same-site requestsCookie

Usually applies to a single domain name

Cookies only apply to a single domain name unless otherwise configured. While this may seem like a limitation on the surface, it is one of the most powerful features to enforce a single source by default. However, if the front end and back end (apis) are from different domain names or subdomains, they need to be explicitly whitelisted in the Cookie. Otherwise, the browser does not send a Cookie with the request.

Not suitable for open apis

If you are building an API to expose services to clients, cookies may not be the best choice. Unless the client is just a browser, it complicates the client.

For example, if you are developing a mobile application, having a Cookie will complicate the management of mobile application cookies compared to the Token.

There may be scalability issues

As mentioned earlier, the server is responsible for Cookie Settings and needs to store sessions in the database for each user.

Although there are sophisticated ways to deal with extensibility (for example, using an in-memory database like Redis as the storage for sessions), it still adds more complexity.

However, as the number of users increases, problems may arise in extending and managing these sessions.

Best for storing additional data

Since this method maintains a separate session for each user, additional data can be stored in the session.

Cookies and sessions allow you to store specific data, such as user personalization, access control, and sessions. It then allows it to be used for subsequent requests.

However, this can also be achieved with tokens. For example, Claims data can be stored using a JWT token. However, since it will increase the Token size, retaining more tokens will affect higher network utilization.

You can restrict browser access to cookies

Because cookies provide the HTTP-only option, JavaScript access to them can be restricted. In addition, it will block any access to cookies with cross-site scripting attacks.

Token based authentication

Token-based authentication was introduced to address the shortcomings of the cookie-based approach.

Unlike cookies, the Token – based approach needs to be implemented on its own, with the Token kept on the client side.

When you log in to the Web application, the server validates the credentials and sends an encrypted Token to the browser. The browser then stores this Token and can add it to the authorization header of subsequent requests.

However, the standard implementation of the Token based approach is much more complex than the process described above. For example, OpenID Connect introduces multiple authentication streams to handle different types of use cases.

To better understand how tokens work, the process is broken down into four parts, using the most widely used Token standard, JWT, as an example.

JSON Web Token (JWT) is the most commonly used open standard for token-based authentication.

Token authentication workflow

1. Use credentials to log in to the application

2. The server verifies the credentials, generates a token, signs it with a key, and sends it back to the browser

Typically, you need to use encryption (such as SSL) to secure channels during transmission.

On the server side, you can use an NPM library like JsonWebToken to generate these tokens.

npm install jsonwebtoken
Copy the code
const jwt = require("jsonwebtoken");
const privateKey =
    "eyJkYXRhIjp7InVzZXJuYW1lIjoiZGV2cG9pbnQifSwiaWF0IjoxNjI3Njk3ODQ2fQ";
const token = jwt.sign(
    {
        data: {
            username: "devpoint",
        },
    },
    privateKey,
    { algorithm: "HS256" },
    { expiresIn: Math.floor(Date.now() / 1000) + 60 * 60 }
);
Copy the code

The Token generated using jsonWebToken looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoiZGV2cG9pbnQifSwiaWF0IjoxNjI3Njk3OTA2fQ.9v0S-74SH5UQwTAq gvNL43fAxQqW3_cajoDsum3TZEoCopy the code
3. Store the Token in the browser store and add it to subsequent requests using JavaScript

The browser can store this Token in the local storage, Session storage, or Cookie. This Token is then added to the authorization header of the necessary request and sent to the server for request validation. Therefore, you need to use JavaScript to implement adding the Token to the header.

Authorization: Bearer <token>
Copy the code

In addition, you can use the jwt.decode() function in the JsonWebToken library to decode this Token and use the payload data in your application.

4. When a user logs out, manually delete the Token from the storage

Once the user exits the system, the tokens stored in the storage need to be manually cleared so that they cannot be used for further requests.

Token authentication features, advantages and disadvantages

A stateless mechanism

Unlike cookies, the token-based approach is stateless. This means that it does not store any information about the user in the database or on the server.

The server is only responsible for creating and validating tokens, which allows you to build more scalable solutions than the cookie-based approach.

Security issues

Although tokens attempt to address security issues in cookies, they are not completely secure.

Tokens saved in the browser can be vulnerable to XSS attacks if the application allows external JavaScript to be embedded in the application.

Also, since the token is stateless, if exposed, there is no way to undo it before it expires. Therefore, it is important to retain as few tokens as possible. Most authentication services set the validity period of JWT tokens to less than 5 minutes.

conclusion

Token-based and cookie-based approaches are the two most commonly used authentication mechanisms for Web applications. In this paper, their working principles, characteristics, advantages and disadvantages are discussed.

As you can see, none of these approaches is 100% perfect, and each has its advantages and disadvantages. Therefore, when choosing an authentication method, it is recommended to choose one based on the project requirements rather than the perfect method.