Mikel Oyarzabal's stunning effort cancelled out Matheus Cunha's opener to force extra-time at International Stadium Yokohama.
There was plenty of drama before normal time was up – Richarlison blazing a penalty over just prior to Cunha's opener before the Everton forward hit the crossbar in the second half, with Oscar Gil and Bryan Gil also hitting the woodwork at the other end.
Yet it was substitute Malcom who ultimately proved decisive, the Zenit winger getting the better of Jesus Vallejo to prod home beyond Unai Simon and seal back-to-back gold medals for Brazil.
Diego Carlos had to clear off the line to prevent an embarrassing own goal in the 16th minute, before Richarlison sliced into the side netting from a tight angle.
The tournament's leading scorer Richarlison should have added to his tally in the 38th minute, after Spain goalkeeper Simon was adjudged to have fouled Cunha after a VAR (video assistant referee) check, but he lashed his spot-kick well over.
Brazil swiftly recovered, though, Dani Alves doing brilliantly to keep a move alive, with Cunha bringing down the looping ball and arrowing a finish into the bottom-right corner.
Simon redeemed himself with a fine save from Richarlison after the break, parrying the forward's effort onto the underside of the crossbar, and Oyarzabal's wonderful 61st-minute strike subsequently restored parity.
The woodwork came to Brazil's salvation late on in normal time, Gil's right-wing centre clipping off the bar before Bryan's thunderous effort rattled off the frame of the goal.
Brazil made its good fortune count in the 18th minute of extra-time, Malcom's turn of pace proving too much for Vallejo, who could only watch on as the former Barcelona man secured its second Olympic gold.
Alves and Spain were in tears at full-time, collapsing on the pitch as Brazil became the fourth team to win successive gold medals in the men's football event, in what was a record-setting fifth final for the Selecao.
Contesting a third Olympic final, Spain – the champion at the Barcelona 1992 Olympic Games – had to settle for silver, the medal it won back in 2000 in Sydney.