Mr Obama praised US troops for reversing the momentum of the TalibanPresident Barack Obama has told US troops in Afghanistan that America's longest war will come to "a responsible end" at the end of 2014, bbc reports.
Mr Obama was cheered by soldiers during the unannounced visit to Bagram Airfield outside Kabul.
It comes on the eve of Memorial Day, when Americans commemorate troops who have died in service.
Foreign combat troops are due to withdraw from the country by the end of the year.
The US is seeking to keep a small number of troops there to train Afghan security forces. But that plan depends on the next Afghan president - due to be elected next month - signing a bilateral security agreement that incumbent Afghan President Hamid Karzai has refused to authorise.
President Obama had invited his Afghan counterpart to the base but Mr Karzai refused, saying he would only meet Mr Obama at his palace in Kabul, officials said.
Criticism at home
To cheers from the assembled troops, Mr Obama thanked them for their service, and promised to improve treatment for wounded veterans.
"By the end of this year... Afghans will take full responsibility for their security and our combat mission will be over. America's war in Afghanistan will come to a responsible end."
Mr Obama said the US would remain committed to Afghanistan provided the incoming president signed the security agreement.
Both of the candidates who will face each other in the second round of the Afghan election next month are committed to signing the security deal with the US that would allow a small force of some 10-15,000 US troops to remain next year.
Afghanistan was at a pivotal moment, he said, with US forces having decimated al-Qaeda, reversing the momentum of the Taliban, and leaving a legacy of better health and education and strong Afghan forces.
"After all the sacrifices we've made we want to preserve the gains that you have helped to win and we're going to make sure that Afghanistan can never again, ever, be used again to launch an attack against our country," he said.
Mr Obama's speech ended with the image of a US flag found, damaged and burned but still intact, in the rubble of the World Trade Center after the 11 September attacks on the US, says the BBC's David Loyn in Kabul.
The visit comes as the president is under criticism at home for the treatment of wounded veterans from the conflict.
He had his biggest cheer from the troops for his commitment to help find jobs for veterans, and look after the wounded, which he described not as a promise but a "sacred obligation", adds our correspondent.
More than 2,100 members of the US military have been killed during nearly 13 years of war in Afghanistan. Thousands more have been wounded.
The Taliban have stepped up attacks ahead of the withdrawal by the Nato-led force.