It comes from trains, bus, ship travel, of course. Everyone must pay the fare and have a ticket. No free rides.
It has come to refer to people who get something from the government, especially people who get benefits they don't deserve or qualify for. As with your example, it's most commonly used to criticize those people.
Compare with "full ride," a phrase that means a college student has earned enough scholarship money to attend college at no cost. This phrase is almost always used in a positive context.