I have been on interviews where this is part of a boiler plate release/waiver for a background check, prior to receiving an offer letter, and on the same form, you are made to list prior employers, and fill in the salary box for each.
And if you don't like it, good luck taking legal action, right? Whether something is legal or illegal, most people lack the resources to even entertain the idea of challenging legality.
The only path that seems to effectively buffer this practice is working with recruiting agencies, which do a better job of negotiating, but do still collect this information. And although recruiters might only be capable of telling you whether you have real leverage for your salary demands, whether the recruiter is being paid by you or the employer is a clue as to who they're working for.
Hint: if you aren't paying them out of pocket, recruiters aren't actually working for you, even if they seem really pleasant.