Sobes.tech
Junior — Middle

Do you have experience using JSON Web Tokens for authorization or authentication?

sobes.tech AI

Answer from AI

Yes, JSON Web Tokens (JWT) are widely used for authorization and authentication in web applications. JWT is a compact, URL-safe way of transmitting information between parties as a JSON object, which can be verified and trusted because it is digitally signed.

In a typical authentication scenario, the user provides login credentials, the server verifies them, and if valid, creates a JWT with a payload (e.g., user_id, roles, expiration time). This token is sent to the client, stored (e.g., in localStorage or cookie), and attached to subsequent requests in the Authorization header.

Example of creating and verifying JWT in Python using PyJWT library:

import jwt
import datetime

SECRET_KEY = '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 decode_token(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        return payload['user_id']
    except jwt.ExpiredSignatureError:
        return None  # Token expired
    except jwt.InvalidTokenError:
        return None  # Invalid token

Thus, JWT allows secure transmission of user information and session management without server-side state.