Describe how token-based mitigation works to prevent CSRF attacks.

Token-based mitigation involves generating a unique token for each user session and embedding it in forms or requests. The server checks the token to verify the legitimacy of the request, preventing unauthorized actions.

Example :
import os
import hashlib
# Generate a CSRF token
def generate_csrf_token():
    return hashlib.sha256(os.urandom(64)).hexdigest()
# Validate the CSRF token
def validate_csrf_token(session_token, form_token):
    return session_token == form_token
# Example usage
session_token = generate_csrf_token()
form_token = session_token  # This would be sent with the form
# Validate the token when the form is submitted
is_valid = validate_csrf_token(session_token, form_token)
print(is_valid)  # Should print True?