Sobes.tech
Middle+

What are JWT tokens used for?

sobes.tech AI

Answer from AI

JWT (JSON Web Token) is used for securely transmitting information between parties in the form of a JSON object. Its main applications are user authentication and authorization in web applications. The token contains encoded data (for example, user ID and access rights) and is signed, which allows verifying its authenticity without querying the database.

Example of usage in Go:

import (
    "github.com/golang-jwt/jwt/v4"
    "time"
)

func GenerateJWT(secret []byte, userID string) (string, error) {
    claims := jwt.MapClaims{
        "sub": userID,
        "exp": time.Now().Add(time.Hour * 72).Unix(),
    }
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    return token.SignedString(secret)
}

Thus, JWT allows storing session state on the client and quickly verifying access rights without constant server requests.