The game was heading for extra time until Mohamed Oulhaj's header was saved by Tamati Williams and fell to the feet of Hafidi who tapped in the rebound to send the Agadir Stadium into delirium.
Raja, who fired coach Mohamed Fakhir and replaced him with Tunisian Faouzi Benzarti last week, qualified as the champions of the host nation while Auckland were representing the Oceania confederation.
The home team went ahead when Mouhssine Iajour slotted a left-foot shot into the far corner six minutes before halftime.
Mohsine Moutaouali curled a shot against the post early in the second half before a defensive blunder allowed Auckland to grab a shock equaliser and silenced the stadium just after the hour.
Two Raja defenders collided, leaving Fijian Roy Krishna an easy chance to score the equaliser past Khalid Askri.
Hafidi spared Raja's blushes with his last-gasp goal to set up a quarter-final tie against Mexican side Monterrey, the champions of CONCACAF, on Saturday.
The winners go on to meet South American champions Atletico Mineiro, who have a bye to the semi-final. European champions Bayern Munich, who also have a bye to the semis, are runaway favourites to win the tournament.