Junior — Middle
On which project did you implement authentication mechanism using JWT?
sobes.tech AI
Answer from AI
In one of my projects, I implemented authentication using JWT for a REST API in Python with the PyJWT library. The user receives a token upon login, which is then sent in the Authorization header when making requests to protected endpoints. The server verifies the token's signature and expiration date before granting access.
Example of creating and verifying JWT in Python:
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 verify_token(token):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
return payload['user_id']
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
This approach allows for secure session management without server-side state storage.