Morocco manager Vahid Halilhodzic took the opportunity to rest several key men, but that decision backfired in the first half, with Gabon well worth its 21st-minute lead.
Jim Allevinah converted past Munir Mohamedi after Nayef Aguerd slipped at the crucial moment, and it might have made it to the break with a bigger lead were it not for the Morocco goalkeeper.
The Atlas Lions thought they had equalised with an hour played when a long ball from the back was missed by Gabon goalkeeper Jean Noel Amonome and went all the way in, but Youssef En-Nesyri was deemed to have been interfering with play in an offside position.
Morocco did get a slice of fortune 16 minutes from time, substitute Sofiane Boufal winning a penalty despite Andre Biyogo Poko appearing to win the ball, and the Angers attacker converted from 12 yards.
Gabon – without Mario Lemina and Pierre-Emerick Aubameyang again – thought it had snatched a win to top the group as Aguerd put into his own net after 81 minutes, but Hakimi's free-kick three minutes later rescued Morocco.