Sobes.tech
Junior — Middle

Explain what a JSON Web Token is and how it is used for authorization?

sobes.tech AI

Answer from AI

JSON Web Token (JWT) is a compact, URL-safe way to transmit information between parties as a JSON object. JWT is often used for authorization and authentication.

JWT consists of three parts separated by dots:

  1. Header — contains token type and signature algorithm.
  2. Payload — contains claims, such as user ID and expiration time.
  3. Signature — created from header and payload using a secret key.

During login, the server issues a JWT to the client after successful authentication. The client stores the token and sends it in the Authorization header for subsequent requests. The server verifies the signature and data to authenticate the user.

Example of creating JWT in Python with PyJWT:

import jwt
import datetime

secret = 'my_secret_key'
payload = {
    'user_id': 123,
    'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}
token = jwt.encode(payload, secret, algorithm='HS256')
print(token)