Substitute Malcom raced in behind and slotted home the winner after 108 minutes to hand Brazil the gold medal.
Five years ago, Neymar scored the winning penalty as Brazil beat Germany to win their first gold on home soil.
Mikel Oyarzabal’s volley for Spain had ruled out Matheus Cunha’s opener in the second half of normal time.
In an enthralling contest between two of football’s biggest heavyweights, Everton forward Richarlison missed a penalty and hit the crossbar.
Spain substitute Bryan Gil also hit the woodwork with a stunning long range strike a minute before extra time.
Brazil were competing in their third successive gold medal match at the Games – following on from the gold they won in Rio and a silver picked up in London 2012.
The 1992 champions Spain were tipped for gold before the tournament started as they had a squad laden with players who featured in this summer’s European Championship.
Among them were Barcelona’s Pedri and Eric Garcia, Villarreal’s Pau Torres and Athletic Bilbao goalkeeper Unai Simon.
The Spaniards struggled to hit top form, despite grinding their way into the final, and did not show enough quality to snatch gold from Brazil.