He gave the speech a year to the day since the death of Osama Bin Laden. The visit was not announced publically, and it was to sign an agreement on future ties with Afghan President Hamid Karzai.
He said in his speech, "My fellow Americans, we have travelled through more than a decade under the dark cloud of war. Yet here, in the pre-dawn darkness of Afghanistan, we can see the light of a new day on the horizon.
"I will not keep Americans in harm's way a single day longer than is absolutely required for our national security. But we must finish the job we started in Afghanistan, and end this war responsibly."
He also outlined the nature of the Afghan pact, saying it outlines plans for training Afghan forces and supporting counter terrorism efforts, as well as "Afghan commitments to transparency and accountability".
He also confirmed that the 2014 removal of US troops from Afghanistan would go ahead as planned, and that pulling out any earlier would be i
Mr Obama signed the pact with Mr Karzai, calling it an “historical moment for both nations”. The agreement comes before a Nato meeting in Chicago.
Hours after Mr Obama’s speech, at least seven people were killed by at least two suicide bombers in Kabul. Official say the target was a guesthouse popular with foreigners, while four of those killed were schoolchildren.