Midfielder Sofiane Boufal, a former Southampton star, but now playing with Al Rayyan in Qatar, gave Morocco the lead after 29 minutes, scoring with a powerful turn and drive from a pass by Bilal El Khannous.
Brazil skipper Casemiro levelled in the 67th minute when his weak shot was fumbled by goalkeeper Yassine Bounou.
But on-loan Sampdoria midfielder Abdelhamid Sabiri struck the winner with a volley in the 79th minute as Morocco showed that becoming the first Arab or African nation to reach the World Cup semi-finals last year was no fluke.
"I wouldn't say we lacked understanding, it's about putting into practice the ideas of a new coach," said Manchester United's Casemiro.
"I think we played a good game and did everything as far as possible to win."
Only 10 of the 23-man squad that took Brazil to a disappointing quarter-final exit at the World Cup made the trip to Morocco for the game.
The injured Neymar was again missing with his number 10 shirt passing to Real Madrid youngster Rodrygo.
Brazil also had a new manager in the dugout with interim coach Ramon Menezes having replaced Tite who stepped down after the World Cup last-eight exit at the hands of Croatia.
The Brazilian Football Confederation (CBF) hopes to be able to announce the name of its new coach before the start of qualifying for the 2026 World Cup in September.
According to Brazilian media, the CBF's first choice is Carlo Ancelotti, currently in charge of Real Madrid.
However, he is not expected to make a decision on his future before the end of the European season.
Before kick-off at the Ibn Batouta stadium, both teams paid tribute to Pele, who died last December at the age of 82.
Until Saturday, Morocco had suffered defeats in their only two other meetings with Brazil -- 2-0 in a 1997 friendly and 3-0 in the group stages of the 1998 World Cup in France.