Get breaking news alerts and special reports. The news and stories that matter, delivered weekday mornings.

The Trump administration cannot withhold millions of dollars in public safety grants from so-called "sanctuary" states, a federal judge in New York ruled Friday.

The "court concludes that defendants did not have lawful authority to impose these conditions," Judge Edgardo Ramos wrote in his 43-page decision.

The attorneys general of New York and six other states had filed suit against the Department of Justice earlier this year, charging the agency had improperly tacked on three immigration-related conditions they had to comply with in order to get grants for criminal justice initiatives.

The grant conditions sought to force local recipients to share information with federal immigration authorities.

Let our news meet your inbox. The news and stories that matters, delivered weekday mornings. This site is protected by recaptcha

SIGN UP FOR BREAKING ALERTS FROM NBC NEWS

"So-called 'sanctuary' policies make all of us less safe because they intentionally undermine our laws and protect illegal aliens who have committed crimes,” then-U.S. Attorney General Jeff Sessions said when he announced the conditions in June.

New York State Attorney General Barbara Underwood countered that, "Local law enforcement has the right to decide how to meet their local public safety needs — and the Trump administration simply does not have the right to require state and local police to act as federal immigration agents.”

New York state Attorney General Barbara D. Underwood speaks on May 15, 2018, in Albany, New York. Hans Pennink / AP file

The suit, which was also filed on behalf of New Jersey, Rhode Island, Connecticut, Virginia, Massachusetts, Virginia and Washington, argued the feds overstepped, because the agency didn't have the legal authority to impose the changes.

The judge ordered DOJ to release more "than $29 million in grant funds that plaintiffs would otherwise use for law enforcement and public safety purposes."

The ruling is the fourth successful legal challenge to the DOJ conditions to date.

The grant funds — which are used for a variety of public safety programs — are named for Edward Byrne, an NYPD officer who was shot to death in 1988 while guarding the home of a Guyanese immigrant who'd been targeted by street gangs.

Underwood called the ruling "a major win for New Yorkers' public safety."

A spokesman for the Department of Justice declined comment.