Mr Obama's visit into Bagram Air Base near Kabul was conducted under the shroud of nightfall.
He met with about 2,000 troops at the U.S. base and told them their work is significant to security at home.
Camouflage-clad soldiers took photos of the president, who gave them hugs and handshakes before stepping up to the podium.
"I have no greater honor than serving as your commander in chief," Mr Obama told the troops to cheers.
"I know it's not easy," he said. "If I thought for a minute that America's vital interests were not served, were not at stake here in Afghanistan, I would order all of you home right away."
"All of that makes America safer, and we are going to keep them on the run," the U.S. president told a crowd of about 2,500 troops and civilians at Bagram Air Base. "Because that is what is going to be required in order to ensure that our families back home have the security that they need."
"The United States of America does not quit once it starts on something. ... We keep at it," he told the troops. "We persevere. And together, with our partners, we will prevail. I am absolutely confident of that."
Earlier, Mr Obama met with Afghan President Hamid Karzai to discuss progress by the Afghan government in improving its ability to lead the country and provide security for its people.
"I want to send a strong message that the partnership between the United States and Afghanistan is going to continue. We have already seen progress with respect to the military campaign against extremism in the region," Mr Obama told Mr Karzai.
"We also want to continue to make progress on ... good governance, rule of law, anti-corruption efforts -- all these things end up resulting in an Afghanistan that is more prosperous, more secure, independent," he added.
The Afghan president said he hoped "the partnership will continue ... toward a stable, strong, peaceful Afghanistan that can sustain itself, that can move forward into the future."
He thanked the United States, highlighting that American taxpayers had helped rebuild his country.
Before his departure, Mr Obama also met with U.S. Ambassador Karl Eikenberry and Gen. Stanley McChrystal, the commander of allied troops in Afghanistan.
|Your name: *|
|Your email: *|
|Recepient's email: *|
|Enter code: *|