The sentence highlights a long-standing belief between Afghanistan and neighbouring Pakistan that the other country does not adequately prevent cross-border militant attacks.
Shah Mohammad and Nazirullah were arrested in 2016 after travelling to Pakistan to hand over information to Pakistan's Inter-Services Intelligence (ISI) agency. They pleaded not guilty but eventually "confessed to their crime" before the military court in the eastern city of Jalalabad, officials said.
Nadim said the accused had shared secret information about attacks and bomb blasts.
Islamabad, in turn, accuses Afghanistan of not doing enough to eradicate Pakistani Taliban militants, many of whom are based in Afghanistan and mostly carry out attacks inside Pakistan.
A defence lawyer representing the two army officials rejected the court's verdict, which was delivered on Tuesday.
"My clients were beaten during the investigations and they were forced to confess. We don't accept the decision and we will appeal," said Toryalai Muqanen.
(With inputs from agencies.)