Brazil are the first nation to retain their Olympic crown since rivals Argentina won consecutive gold medals in 2004 and 2008.
Spain have to settle for the silver medal and have now failed to win the event since they hosted the Olympic Games in 1992.
A tense first-half came to life after 42 minutes when Brazil were awarded a penalty after VAR adjusted Spain goalkeeper Unai Simon to have fouled Cunha inside the box.
However, Richarlison stepped up to take the spot kick but blazed it over the crossbar.
Brazil took the lead minutes later when Cunha took down Dani Alves‘ looping cross inside the box and produced a composed finish into the corner.
Brazil almost made it 2-0 six minutes after the break but Richarlison’s close-range effort was saved onto the bar by Simon.
Spain made Brazil rue that missed chance and equalised after 61 minutes when Oyarzabal volleyed home from Carlos Soler‘s cross.
Brazil were the more positive side and were rewarded for their attacking display in the second half of extra-time when Malcom finished off a stunning counterattack.