Brazil are the first nation to retain their Olympic crown since rivals Argentina won consecutive gold medals in 2004 and 2008.
Spain settled 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.
"I was unlucky," Richarlison said postmatch. "The important thing is that we scored. All the sacrifice that I've made in my club, during training has been worth it. This group deserves this."
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.
"I'm happy to have achieved the aim," Brazil captain Dani Alves said after winning his fifth title with his country but his first Olympic medal. "We knew we were going to have a tough day against Spain because it's a very difficult rival. Our strategy worked out. I must be honest, this is one of the happiest days in my career. To have been selected for the Olympics and be here was already a victory for me.
"It was an honour. I knew it was a unique opportunity for me. Things have worked out well and we leave with the biggest prize of all. Now all I'm missing is the World Cup! Let's see if I can continue to play. Football changes and to dream is free but to execute those dreams, is more difficult."
Spain coach Luis De la Fuente added: "I'm proud of my players and I'm happy with what we have achieved in these 40 days. We have been able to compete with elegance until the end and I'm proud of that. It's normal that the players are sad and frustrated after this game. Once they rest, they will give this medal the importance it has. I see an extraordinary future ahead because we have very talented players."