After a quarter of an hour, Spain had enjoyed most of the possession early on, although Brazil had been growing into it.
With half an hour gone things had levelled out. Both sides had chances - Mikel Oyarzabal had a header cleared off the line and Richarlison hit the Spanish side netting - but neither side had taken full control of the game.
Brazil won a penalty in the 36th minute after Unai Simon clattered Matheus Cunha after missing his punch and collided with Cunha. Richarlison stepped up but the Everton man blazed his spot-kick high and wide of the target.
The Seleccao would, however, take the lead on the stroke of half-time. Dani Alves swung the ball in and it fell kindly to Matheus Cunha in the box, who chested it down and buried the finish into the bottom right corner.
La Roja levelled on the hour mark. Carlos Soler was played in down the right-hand side and he teed up it up to the back post for Oyarzabal, who finished brilliantly with his left foot on the volley leaving Santos with absolutely no chance.
Zenit Saint Petersburg forward Malcom was brought onto brilliant effect in extra-time and made the instant impact in the 108th minute when being played through on goal and slotting on his left foot across Simon and into the far corner although it was almost saved by the outstretched left leg of the Athletic Bilbao keeper to secure the gold medal and make himself the hero of a nation.