Sobes.tech
Senior

What is JWT and Cookie, and how do they differ?

sobes.tech AI

Answer from AI

JWT (JSON Web Token) is a compact, URL-safe token used for transmitting information between parties as a JSON object. It is commonly used for authentication and authorization: the server issues a JWT to the client after a successful login, and the client sends this token with each request to verify its identity. JWT contains three parts: a header, a payload, and a signature, which ensure integrity and authenticity.

Cookie is a mechanism for storing data on the client side, which the browser automatically sends to the server with each request to the corresponding domain. Cookies are often used to store session identifiers, user settings, and other data.

Main differences:

  • Storage location: JWT is usually stored in localStorage or sessionStorage, while Cookie is stored in the browser and sent automatically with requests.
  • Automatic sending: Cookies are sent automatically by the browser, JWT needs to be manually added to request headers (e.g., Authorization).
  • Security: Cookies can be protected with HttpOnly and Secure flags, reducing the risk of XSS attacks. JWT stored in localStorage is vulnerable to XSS.
  • Usage: JWT is a token format for transmitting information, Cookie is a method of storing and transmitting data between client and server.

Example of using JWT in Go:

// Creating a JWT token
import (
    "github.com/dgrijalva/jwt-go"
    "time"
)

token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    "user_id": 123,
    "exp": time.Now().Add(time.Hour * 72).Unix(),
})
signedToken, err := token.SignedString([]byte("secret"))

Cookie is set in the HTTP response:

http.SetCookie(w, &http.Cookie{
    Name:  "session_id",
    Value: "abc123",
    Path:  "/",
    HttpOnly: true,
})