Middle+
What is a JWT token? What is its structure and advantages over regular tokens?
sobes.tech AI
Answer from AI
JWT (JSON Web Token) is a compact, URL-safe token for transmitting information between parties in the form of a JSON object. It is often used for authentication and authorization.
JWT Structure: JWT consists of three parts, separated by dots:
- Header — contains the token type (JWT) and signing algorithm (e.g., HS256).
- Payload — contains claims, such as user ID, token expiration time.
- Signature — created by hashing the header and payload with a secret key.
Example JWT:
header.payload.signature
Advantages of JWT over regular tokens:
- Self-contained: contains all necessary information, no need to check a database.
- Security: signature guarantees integrity and authenticity.
- Lightweight transmission: compact and URL-safe format.
- Versatility: can be used across different protocols and platforms.
Example of creating a JWT in Go using the github.com/golang-jwt/jwt library:
import (
"github.com/golang-jwt/jwt"
"time"
)
func CreateJWT(secret []byte) (string, error) {
claims := jwt.MapClaims{
"user_id": 123,
"exp": time.Now().Add(time.Hour * 72).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(secret)
}