The decision that eases pressure on Somalis who feared the camp would close by the end of May.
Kenya's Internal Security Minister abused his power by ordering the closure of Dadaab camp, Judge John Mativo said, adding that the Minister and other officials had "acted in excess and in abuse of their power, in violation of the rule of law and in contravention of their oaths of office."
Rights groups Amnesty International, Kituo cha Sheria and the Kenyan National Commission on Human Rights had challenged the government's order to close the camp.
The judge called the order discriminatory, saying it goes against the Kenyan constitution as well as international treaties that protect refugees against being returned to a conflict zone.
President Uhuru Kenyatta's government has not proved Somalia is safe for the refugees to return, the judge said, also calling the orders to shut down the government's refugee department "null and void."
Somalia remains under threat of attacks from homegrown extremist group al-Shabaab.
Some Kenyan officials have argued that the sprawling refugee camp near the border with Somalia has been used as a recruiting ground for al-Shabaab and a base for launching attacks inside Kenya.
But Kenyan officials have not provided conclusive proof of that.
US President Donald Trump's temporary ban on travel for citizens of seven majority-Muslim countries, including Somalia, had put added pressure on the Dadaab refugees. Last weekend, about 140 of the Somali refugees who had been on the brink of resettling in the United States were sent back to Dadaab instead.
Said Abuka, a community leader in Nairobi and a refugee for 22 years, said the court ruling would help the Somali refugees.
Newborn babies could not be registered as refugees because of the shutdown of Kenya's refugee department, he said.
"After months of anxiety because of the camp closure deadline hanging over their heads, increasingly restricted asylum options and the recent US administration suspension of refugee resettlement, the court's judgment offers Somali refugees a hope that they may still have a choice other than returning to insecure and drought-ridden Somalia," said Laetitia Bader, Africa researcher at Human Rights Watch.
Al-Shabaab has carried out several attacks on Kenya, which sent troops to Somalia in 2011 to fight the militants. The attacks include the September 2013 attack on Westgate mall that killed 67 people and the 2015 attack on Garissa University that killed 148 people, mostly students.