import jwt # For decoding JWTs
import datetime # For handling timestamps
import logging # For logging anomalies
# Configure logging
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
def validate_token(token, expected_iss, expected_aud, expiry_window_hours=24):
"""
Validates an authentication token and flags anomalies.
Args:
token (str): The authentication token to validate.
expected_iss (str): The expected issuer of the token.
expected_aud (str): The expected audience of the token.
expiry_window_hours (int): How many hours after expiry to flag.
Returns:
bool: True if the token is valid, False otherwise.
"""
try:
# Decode the token
decoded_token = jwt.decode(token, options={"verify_signature": True})
# Check if token is expired
if decoded_token['exp'] < datetime.datetime.utcnow():
logging.warning(f"Token expired: {token}")
return False
# Check issuer
if decoded_token['iss'] != expected_iss:
logging.warning(f"Incorrect issuer: {decoded_token['iss']} != {expected_iss} in token: {token}")
return False
# Check audience
if decoded_token['aud'] != expected_aud:
logging.warning(f"Incorrect audience: {decoded_token['aud']} != {expected_aud} in token: {token}")
return False
# Check for unusual expiry time (e.g., very far in the future)
if decoded_token['exp'] > datetime.datetime.utcnow() + datetime.timedelta(hours=expiry_window_hours):
logging.warning(f"Unusually long expiry time: {decoded_token['exp']} in token: {token}")
return False
return True # Token is valid
except jwt.ExpiredSignatureError:
logging.warning(f"Token expired: {token}")
return False
except jwt.InvalidTokenError:
logging.warning(f"Invalid token: {token}")
return False
except Exception as e:
logging.error(f"Error validating token: {e} in token: {token}")
return False
if __name__ == '__main__':
# Example usage
valid_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjI3ODg2MDQ4fQ.EXAMPLE_SIGNATURE"
expired_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjI3ODg2MDQ4fQ.ANOTHER_SIGNATURE"
invalid_issuer_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjI3ODg2MDQ4fQ.A_DIFFERENT_SIGNATURE"
print(f"Valid token: {validate_token(valid_token, 'my_iss', 'my_aud')}")
print(f"Expired token: {validate_token(expired_token, 'my_iss', 'my_aud')}")
print(f"Invalid issuer token: {validate_token(invalid_issuer_token, 'my_iss', 'my_aud')}")
Add your comment