Michael Cohen’s First Amendment rights were violated when he was ordered back to prison on July 9 after probation authorities said he refused to sign a form banning him from publishing the book or communicating publicly in other manners, US District Judge Alvin K Hellerstein said.
Judge Hellerstein ordered Mr Cohen to be released from prison by 2pm on Friday.
The Bureau of Prisons in a statement said any assertion that the re-imprisoning of Mr Cohen was a retaliatory action is “patently false”.
Cohen, 53, sued federal prison officials and Attorney General William Barr on Monday, saying he was ordered back to prison because he was writing a book to be released before the November presidential election.
He has been in isolation at an Otisville, New York, prison camp.
The lawsuit said the book would address “Trump’s personality and proclivities, his private and professional affairs, and his personal and business ethics”.
The lawsuit said the government’s demand that Mr Cohen agree not to speak to or through any media, including by publishing a book, violated his First Amendment rights.
Mr Cohen had been furloughed in May along with other prisoners as authorities tried to slow the spread of coronavirus in federal prisons.
He was one year into a three-year prison sentence after pleading guilty to campaign finance charges and lying to Congress, among other crimes.
Campaign finance charges related to his efforts to arrange payouts during the 2016 presidential race to keep the porn actress Stormy Daniels and model Karen McDougal from making public claims of extramarital affairs with President Trump – who has denied the affairs.