Sobes.tech
Middle+

Evaluate the following authorization implementation: login/password form, backend searches for a user in the database (table: id, username, password), takes an integer ID and writes it into a cookie with HttpOnly flag. What's wrong with this implementation and how to fix it?

sobes.tech AI

Answer from AI

The described implementation has several issues:

  1. Storing user ID directly in a cookie — this is insecure, as cookies can be forged or stolen, and an attacker could access someone else's account by substituting their ID.

  2. Lack of cookie authenticity verification mechanism — there is no signature or encryption to ensure the cookie has not been tampered with.

  3. No expiration time and protection against replay attacks.

  4. HttpOnly is good, but not enough. Secure (HTTPS only) and SameSite flags should be used to restrict cookie access.

How to fix:

  • Instead of storing user ID in a cookie, use a session identifier or a signed JWT.
  • If sessions are on the server, store only a unique session key in the cookie, and keep user data on the server.
  • If using JWT, sign the token with a secret to prevent forgery.
  • Always use Secure, HttpOnly, and SameSite flags for cookies.
  • Add session expiration and renewal mechanisms.

Example with JWT:

// Upon successful login, create a JWT with the user ID
// and sign it with a secret

// On the client, only the JWT is stored in the cookie
// The server verifies the signature and extracts the ID from the token

Thus, security is improved, and the risk of cookie forgery is reduced.