Summary:
You can defend against enemy spies by establishing counter-intelligence. To do this, move a spy into one of your cities that you suspect will be a target (usually a city with a high science output). Once there, they have a chance to detect enemy spies. The higher the rank of the spy, the better their chance to detect an enemy spy.