BRASÍLIA—Brazilian lawmakers advanced legislation that would hamper the ability of prosecutors and judges to go after crooked politicians, potentially setting back the country’s fight against widespread corruption.

In a vote in the wee hours of Wednesday morning, deputies in the nation’s lower house approved a measure that allows defendants to sue judicial authorities who abuse their powers. Prosecutors and judges could be fined and sentenced to prison for alleged offenses including damaging the “honor, dignity and decorum”...