Morocco thought they had gone ahead after 15 minutes when Ismael Saibari headed into the back of the net, but his effort was ruled offside.
A number of headed efforts by Morocco went begging in the first half, with Ayoub El Kaabi the main culprit.
Just four minutes into the second half, Tanzania goalkeeper Hussein Maasalanga was called in to save Neil Yoni El Aynaoui's determined shot.
But the East Africans shook the hosts shortly after, with Feisal Salum missing the target by a whisker from a distance.
Achraf Hakimi almost thrust the home side ahead, but hit the crossbar on the hour mark as Morocco piled more pressure.
Then, four minutes later, Brahim Diaz picked a pass from Hakimi and went for the kill to beat Masalanga and break the deadlock when some of his teammates expected a cross.
It ended 1-0 in favour of Morocco with Diaz the hero of the evening.