Tuesday's court ruling relates to conditions introduced in 2004 on the right of migrants from the EU and European Economic Area who are "economically inactive" and their family members to claim certain benefits, known as the "habitual residence" test.
The European Commission had argued that the British process of checking whether claimants of child benefit and child tax credit were legally resident discriminated against foreign EU workers because British citizens were not checked in the same way.
The court said the condition might amount to "unequal treatment" but did not go beyond what was necessary to attain the "legitimate objective" of protecting a member state's finances.
Analysis by BBC political correspondent Theo Leggett
This was a vital victory for the government, in a case that was potentially explosive during a closely fought referendum campaign.
Although the ruling focused on a complex point of law, the case itself affected a key plank of government policy - the right to restrict benefits for EU migrants who are not considered "economically active".
Although this particular legal battle actually began several years ago, the prime minister recently put further benefit curbs at the heart of his EU renegotiations.
So losing the case would certainly have come as a major embarrassment for Mr Cameron and those campaigning to remain in the EU. In the event, the court sided with the government. Yes, its rules treated people unequally, the judges said, but that was allowed to protect the country's finances.
The Remain campaign may now be breathing a large sigh of relief. However, Vote Leave may not be too unhappy either; they can point to the fact that a major decision about the government's policy has just been taken by judges in Luxembourg.
"The court rejects the Commission's principal argument, that the UK legislation imposes a condition supplementing that of habitual residence contained in the regulation," it ruled.
"There is nothing to prevent the grant of social benefits to EU citizens who are not economically active being made subject to the requirement that those citizens fulfil the conditions for possessing a right to reside lawfully in the host member state."
This issue covers immigration and free movement within Europe.
What the leave and remain sides are saying about immigration in the #EUref campaign
Total net migration to the UK is running at over 300,000 a year despite the government’s target of cutting it to under 100,000
The most recent official figures put net migration from EU countries at 184,000 a year and non-EU at 188,000
EU citizens have the right to live and work in any member state
It is impossible to control immigration as a member of the EU
Public services are under strain because of the number of migrants
High immigration has driven down wages for British workers
Points-based system for migrants to the UK should be extended to include those from the EU
Immigrants, especially those from the EU, pay more in taxes than they take out
Cameron's EU deal means in-work benefits for new EU migrant workers will be limited for the first four years
Outside the EU the UK would still have to accept free movement to gain full access to the single market
Immigration is good for the economy
EU referendum issues guide: Explore the argumentshttp://www.bbc.co.uk/news/uk-politics-eu-referendum-36027205http://www.bbc.co.uk/news/special/2016/newsspec_13606/content/iframe/english/index.inc.app.htmlExplore all the issuesChoose an issue:What both sides are sayingAll issuesMain viewsShare this pageEU referendum issues guideWhat the leave and remain sides are saying in the #EUref campaign
In response, a government spokesman said: "The UK welcomes the judgment, which supports our view that we are entitled to ensure only EU migrants who have a right to be in the UK can claim our benefits.
"Once again this confirms that member states have the ability to protect their own national welfare systems.
"The government has taken action to ensure we have a fair system which provides support for genuine workers and jobseekers but does not allow people to come to this country and take advantage, and today's judgment supports this."
The ruling was welcomed by those campaigning to keep Britain in the European Union.
"This ruling is a victory for Britain, confirming we have a fair immigration system as well as having full access to the EU single market," said Catherine Bearder, a Liberal Democrat MEP.
"The right to travel and work abroad is a two-way street, around 1.2 million Brits choose to live in the EU."
But former work and pensions secretary Iain Duncan Smith, a Leave campaigner, said the European Commission should never have been able to challenge the UK's actions in the first place.
"As well as the cost to taxpayers of fighting these lengthy drawn-out cases, it's clearly an illegitimate challenge to our sovereignty," he said.
"Although David Cameron didn't want to admit it, this case and others like it are proof positive that the unelected European Court of Justice is now supreme above our elected Parliament."
The left-leaning IPPR thinktank said the judgement was a sign the Court was "becoming more sympathetic" to the UK's interpretation of the EU's free movement rules - which is that they do not give migrants an unconditional right to claim benefits.
But it said that there was "no guarantee" that this would last for ever and "future judgments may go against the UK".
The ruling will have no direct impact on the welfare changes secured by David Cameron as part of his renegotiations of the UK's EU membership - which concluded in February.
The prime minister had wanted a complete ban on migrants sending child benefit abroad but had to compromise after some eastern European states rejected that and also insisted that existing claimants should continue to receive the full payment.
As a result, child benefit for the children of EU migrants living overseas will now be paid at a rate based on the cost of living in their home country - applicable immediately for new arrivals and from 2020 for the 34,000 existing claimants.