The European Court of Justice, the 28-nation bloc's top court, threw out the challenge from Hungary and Slovakia against a scheme Brussels launched two years ago to ease the burden on overstretched Greece and Italy.
Europe has been grappling with the worst migrant crisis since World War II, with hundreds of thousands of people fleeing war, persecution and poverty in the Middle East and Africa.
"The court dismisses the actions brought by Slovakia and Hungary against the provisional mechanism for the mandatory relocation of asylum seekers," the Luxembourg-based court said.
The continuing crisis peaked in 2015. More than 1.6 million people have landed on Greek and Italian shores since 2014.
More From This Section
The verdict was welcomed by the European Commission, the executive of the 28-nation bloc.
"ECJ confirms relocation scheme valid. Time to work in unity and implement solidarity in full," said EU Migration Commissioner Dimitris Avramopoulos.
However, Hungarian Foreign Minister Peter Szijjarto slamed the verdict as "irresponsible," saying it "threatens the security of all of Europe".
Hungarian Prime Minister Viktor Orban has called migration the "Trojan Horse of terrorism."
In its verdict, the court upheld the right of EU institutions to respond "swiftly to an emergency situation" over the massive migrant influx.
It also held that the European Council, the body of member states, "was not required to act unanimously when it adopted the contested decision".
A majority of EU member states decided in September 2015 to relocate 120,000 Syrian and other asylum seekers from overstretched Greece and Italy to most of the other 28 EU member states.
Officials in Brussels have argued that the scheme is legally binding on member states, including those that voted against the quotas like Hungary, Slovakia, the Czech Republic and Romania.
Poland initially supported the plan but has come out strongly opposed since a right-wing government came to power.
The court statement said Poland intervened in support of Hungary during the proceedings, while the European Commission, along with Greece, Italy, Germany, Sweden and several other member states, argued for the relocation plan.
Eastern European member states opposed the plan, saying they were not equipped to integrate people from mainly Muslim countries.
It was introduced as an exception to the so-called Dublin rules under which migrants must apply for asylum in the member state where they first land.