The European Court of Justice has rejected efforts by Hungary and Slovakia to stay out of a European Union scheme meant to relocate refugees.
The court said that it had "dismissed in its entirety the actions brought by Slovakia and Hungary".
EU countries agreed in September 2015 to relocate 160,000 refugees in Greece and Italy over two years. Only around 24,000 people have been relocated so far.
The programme is considered a key part of the EU's migration policy.
Hungary and Poland voted against the plan and have refused to take part while so far Slovakia has accepted only a handful of refugees from Greece.
Human rights group Amnesty International has welcomed the ruling on the relocation of asylum seekers, saying Slovakia and Hungary have been trying to turn their countries into "refugee-free zones".
The group's EU office director, Iverna McGowan, said that "Slovakia and Hungary have tried to dodge the EU's system for solidarity, but each country has a role to play in protecting people fleeing violence and persecution".
She called on EU nations to "show solidarity with each other, and with asylum seekers who are seeking protection in Europe".
The Hungarian Helsinki Committee, an advocate for asylum seekers, urged Hungary to give refugees an opportunity to make their case for asylum.
"The lesson of the verdict is that helping people fleeing war and terror is truly a common responsibility for Europe," the group said. "Hungary needs to respect the decision of the EU court."
Besides Hungary's legal arguments against the EU plan, Prime Minister Viktor Orban's government has also made the case and the issue the focal point of its political activities since early 2015 and ahead of parliamentary elections expected in April 2018.
Hungary's position is that only its elected leaders should be able to decide who is allowed into the country. Mr Orban has said that the large influx of mainly Muslim immigrants threatens Europe's and Hungary's cultural identity.
From mid-September 2015, Hungary closed off its southern border first with Serbia and later with Croatia, with a fence protected by razor wire.
The fences have mostly stopped migrants from passing through Hungary on their way to western Europe but Hungary has also greatly reduced the chances for asylum seekers to submit applications for protection in the country.