Chief Justice John G. Roberts Jr. on Thursday joined the Supreme Court’s liberals to save the heart of President Obama’s landmark health-care law, agreeing that the requirement for nearly all Americans to secure insurance is permissible under Congress’s taxing authority.

The court’s 5 to 4 ruling was a stunning legal conclusion to a battle that has consumed American politics for two years. Roberts’s compromise offered a dramatic victory for Obama and Democrats’ decades-long effort to enact a health-care law and a bitter defeat for Republicans and tea party activists, who had uniformly opposed the Patient Protection and Affordable Care Act.

The decision keeps in place the largest new social program in a generation, a major overhaul of the health-care system that could extend coverage to about 30 million Americans. It creates state-run insurance exchanges and eliminates what have been some of the most unpopular insurance practices.

The ruling did limit one significant portion of the law, which sought to expand Medicaid to cover millions more poor and disabled people. The program is a joint federal-state effort, and the court said the law’s requirement that states rapidly extend coverage to new beneficiaries or lose existing federal payments was unduly coercive.

Obama welcomed the justices’ decision, which he called “a victory for people all over this country whose lives will be more secure.”

At the core of the legislation is the mandate that Americans obtain health insurance by 2014.

The high court rejected the argument, advanced by the Obama administration, that the individual mandate is constitutional under the Commerce Clause of the Constitution. Before Thursday, the court for decades had said it gave Congress latitude to enact economic legislation.

But Roberts found another way to rescue it. Joined by the court’s four liberal justices — Ruth Bader Ginsburg, Stephen G. Breyer, Sonia Sotomayor and Elena Kagan — he agreed with the government’s alternative argument, that the penalty for refusing to buy health coverage amounts to a tax and thus is permitted.

Roberts summed up the split-the-difference decision: “The federal government does not have the power to order people to buy health insurance,” he wrote. “The federal government does have the power to impose a tax on those without health insurance.”

The chief justice went out of his way several times to portray the court as a neutral arbiter of the facts, adjudicating matters of law, not passing judgment on the wisdom of the health-care legislation.

“Those decisions are entrusted to our nation’s elected leaders, who can be thrown out of office if the people disagree with them,” Roberts said. “It is not our job to protect the people from the consequences of their political choices.”

It was a mark of the tightrope Roberts walked that, after announcing the court’s decision, he sat impassively while representatives of the court’s conservative and liberal wings read forceful criticisms of his work.

Justice Anthony M. Kennedy, most often the pivotal vote in the court’s ideological battles, said the law is an affront to individual liberty and should have been rejected in its entirety.

“The values that should have determined our course today are caution, minimalism and the understanding that the federal government is one of limited powers,” said Kennedy, who spoke for Justices Antonin Scalia, Clarence Thomas and Samuel A. Alito Jr.

“The court’s ruling undermines those values at every turn.”

From the left, Ginsburg criticized Roberts’s decision to join the conservatives in saying the Commerce Clause does not provide Congress the power to require buying health insurance.

Such a ruling, she said, is an excavation of the court’s pre-New Deal decisions that “routinely thwarted legislative efforts to regulate the economy in the interest of those who labor to sustain it.”

Breyer, Sotomayor and Kagan agreed with her.

The legal battles over the health-care legislation began, literally, moments after Obama signed it into law. Dozens of lawsuits nationwide challenged it. The Supreme Court agreed to hear a suit brought by Florida and 25 other states, as well as a challenge brought by the National Federation of Independent Business.

The challenges were initially dismissed as harmless, but an argument took hold to illustrate the unlimited power Congress was assuming: that if it could do this, it could require Americans to buy broccoli.

It was especially bitter for the conservative legal movement that five members of the court — including Roberts — embraced most of their arguments, and it still lost the war.

Roberts wrote that he agreed with challengers, that Congress and the administration were arguing that the Commerce Clause gives the federal government the power to require its citizens to do almost anything, “to act as the government would have them act.”

“This is not the country the Framers of our Constitution envisioned,” Roberts wrote.

Joined by the conservatives, he also rejected the argument that requiring health-care coverage was different, because everyone at some point will require medical care.

“The Commerce Clause is not a general license to regulate an individual from cradle to grave, simply because he will predictably engage in particular transactions,” he wrote.

But Roberts said it is the court’s duty to look for ways in which acts of Congress can be upheld, and he found it in Congress’s taxing power, a point pressed during oral arguments by Solicitor General Donald B. Verrilli Jr.

Roberts acknowledged that the law refers to the “shared responsibility payment” due on a person’s 2014 tax returns if he or she does not obtain health insurance as a penalty, not a tax. But he noted that it was calculated as a portion of a person’s income and due to the Internal Revenue Service.

And Congress frequently imposes taxes, such as cigarette taxes, to encourage people to quit smoking.

“Upholding the individual mandate under the Taxing Clause thus does not recognize any new federal power,” Roberts wrote. “It determines that Congress has used an existing one.”

Kennedy said Roberts and the justices who joined him rewrote the statute in order to save it.

“The act requires the purchase of health insurance and punishes violation of that mandate with a penalty,” Kennedy said. “But what Congress called a ‘penalty,’ the court calls a tax. What Congress called a ‘requirement,’ the court calls an option. . . . In short, the court imposes a tax when Congress deliberately rejected a tax.”

On Medicaid, Roberts said Congress crossed a line in threatening states with the loss of existing funding if they did not comply with the new requirements, even if the federal government for now was footing the bill.

He said Congress may offer money to entice the states, but may not withdraw funding as a threat.

The conservatives, though, said the solution Roberts offers puts the states in the same coercive place.

“States must choose between expanding Medicaid or paying huge tax sums to the federal fisc for the sole benefit of expanding Medicaid in other states,” Kennedy wrote.

“If this divisive dynamic between and among states can be introduced at all, it should be by conscious congressional choice, not by court-invented interpretation.”

The three cases the Supreme Court considered were National Federation of Independent Business v. Sebelius; Florida, et al., v. Department of Health and Human Services; and Department of Health and Human Services v. Florida, et al.