Sobes.tech
Junior — Middle

How is user authentication performed using JWT?

sobes.tech AI

Answer from AI

User authentication using JWT (JSON Web Token) typically occurs as follows:

  1. The user sends their credentials (e.g., login and password) to the server.
  2. The server verifies the data, and if correct, creates a JWT containing a payload with user information and token expiration time.
  3. The token is signed with a secret key and sent to the client.
  4. The client stores the token (e.g., in localStorage or cookies) and includes it in the Authorization header for subsequent requests.
  5. When the server receives a request, it extracts the token, verifies its signature and expiration, and if everything is in order, grants access to protected resources.

Example in Python using the PyJWT library:

import jwt
import datetime

SECRET_KEY = 'your_secret_key'

def create_token(user_id):
    payload = {
        'user_id': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return token

def verify_token(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        return payload['user_id']
    except jwt.ExpiredSignatureError:
        return None  # Token has expired
    except jwt.InvalidTokenError:
        return None  # Invalid token

Thus, JWT allows secure transmission of user information between client and server without the need to store sessions on the server.