The North Africans followed in the footsteps of Gabon, who sealed a first appearance at the game just yesterday in Tangiers when Andre Biyogho Poko headed the only goal against Senegal in the last minute of extra time.
Egypt and Senegal get another chance to reach London when they meet on Saturday for third place and even defeat will not spell the end as the losers face the fourth-place team in the Asian qualifiers for another chance next April.
Morocco made three changes after a shock 1-0 loss to Senegal in their final group game with Germany-based goalkeeper Younes Itra given a first start ahead of Yassine El Kharroubi.
After managing just two goals in three mini-league matches, the tournament hosts took only 30 seconds to edge ahead as Soufiane Bidaoui dribbled past several defenders and his cut-back was tapped into the net by Abdelaziz Barrada.
The 22-year-old midfielder from La Liga club Getafe struck again with nine minutes gone, poking a loose ball over the line after Egypt goalkeeper Ahmed El Shenawy failed to hold an Adnane Tighadouini drive.
Egypt, who have represented Africa at the Olympics a record ten times, held their nerve and attacked a fragile Moroccan rearguard only to have two shots cleared off the line and another rebound from the base of a post.
But a much deserved goal for the visitors finally arrived on 36 minutes when a Marwan Mohsen cross was picked up by Mohamed Salah and he punished sloppy defending to drive the ball across Itra and into the far corner.
The pace understandably slackened during the second half until a Barrada run and a Bidaoui cut-back set up Younes Mokhtar for a third Moroccan goal midway through the half. Egypt still refused to surrender and after substitute Ahmed Shokry headed against the woodwork, Ahmed Abdelbaset scored from close-range to trigger a tense finish.