While the Socialists have a minority of just 84 seats in the 350-seat assembly, the measure introduced by Prime Minister Pedro Sanchez shortly after he came to power in June passed with 177 votes in favour and 133 against.
It grants undocumented migrants access to public health “under the same conditions as people who have Spanish nationality.”
Sanchez's conservative predecessor Mariano Rajoy withdrew the right to public healthcare for undocumented migrants in 2012 as part of a programme of spending cuts as Spain grappled with a financial crisis.
Several regional governments responded by giving undocumented migrants access to healthcare and Rajoy's government in 2015 reinstated access to emergency healthcare.
“Health does not know borders, identity papers, or work permits,” Health Minister Carmen Monton told lawmakers before the measure was voted on.
Sanchez, who came to power after ousting Rajoy in a no-confidence vote, made global headlines in June by offering to take in a rescue ship that was drifting in the Mediterranean sea with 629 migrants on board. Italy and Malta had refused to let it dock.
The law resorting healthcare for undocumented migrants was approved with the support of the coalition of far-left and smaller regional parties which backed the Socialists in their no-confidence vote against Rajoy.
Conservative lawmaker Teresa Angulo accused the government of “opening wide the doors of Spain to health tourism”.
Parliament also passed a law creating over 300 public jobs aimed at processing migrants and asylum seekers.
Spain has become the main entry point for migrants arriving in Europe, after Italy and Greece. Over 33,000 migrants have arrived in Spain by sea and land so far this year, according to the International Organization for Migration.