"We can see the light of a new day on the horizon," he said. "We have a clear path to fulfill our mission in Afghanistan, while delivering justice to al Qaeda."
Mr. Obama spoke after he and Afghan President Hamid Karzai signed the Strategic Partnership Agreement, which ensures U.S. military and financial support for Afghanistan beyond 2014, when the final U.S. combat troops will withdraw. Obama said American forces will be involved in counter-terrorism and training of the Afghan military, "but we will not build permanent bases in this country, nor will we be patrolling its cities and mountains."
The president arrived at Bagram Air Field under the cover of darkness and was greeted by Ryan Crocker, the U.S. ambassador to Afghanistan. Security was extremely tight as the president flew to the nation's capital to meet with Karzai.
Late Tuesday night, just three hours after the president left the country, three different explosions occurred in Kabul. The Taliban is claiming credit.
"We must give Afghanistan the opportunity to stabilize. Otherwise, our gains could be lost, and al Qaeda could establish itself once more," Mr. Obama said. "As Commander-in-Chief, I refuse to let that happen."
The deal does not commit the U.S. to any specific troop presence or spending. But it does allow the U.S. to potentially keep troops in Afghanistan after the war ends for two specific purposes: continued training of Afghan forces and targeted operations against al Qaeda, which is present in neighboring Pakistan but has only a nominal presence inside Afghanistan.
"I will not keep Americans in harm's way a single day longer than is absolutely required for our national security," Mr. Obama said. "But we must finish the job we started in Afghanistan, and end this war responsibly."
The agreement is designed to send a strong message to the region that the U.S. is not abandoning the country.
The president also met with U.S. troops to thank them for their sacrifices. This is Mr. Obama's third trip to Afghanistan since becoming president.
ABC News and The Associated Press contributed to this report.