A federal judge ruled that the measure violated the U.S. government’s right to enforce its laws and was a threat to public safety.