WASHINGTON — President Obama halted the withdrawal of American military forces from Afghanistan on Thursday, announcing that the United States will keep thousands of troops in the country through the end of his term in 2017 and indefinitely prolonging the American role in a war that has already lasted 14 years.

In a brief statement from the Roosevelt Room in the White House, Mr. Obama said he continued to oppose the idea of “endless war.” But the president, who once traveled to Afghanistan to declare “the light of a new day on the horizon,” said Thursday that a longer-term American presence there was vital to the security of the United States and a country that is beset by the Taliban, their allies from Al Qaeda, and militants from the Islamic State.

“While America’s combat mission in Afghanistan may be over, our commitment to Afghanistan and its people endures,” said Mr. Obama, flanked by Vice President Joseph R. Biden Jr. and top military leaders. “I will not allow Afghanistan to be used as safe haven for terrorists to attack our nation again.”

The decision, reached after what White House officials called an “extensive, lengthy review,” ensures that Mr. Obama will leave office in 15 months without making good on a seminal promise of his presidency: to responsibly end the military involvements started by his predecessor, George W. Bush, and withdraw all American troops from the battlefields of Iraq and Afghanistan.