Neymar had put the hosts ahead with a superb free kick after 27 minutes but Germany captain Maximilian Meyer equalized just before the hour to take the game into the extra period at 1-1.
In front of 78,000 at the Maracana, Brazil got a measure of revenge as they finally won the Olympic title after losing in the finals in 1984, 1988 and 2012.
Two years ago, World Cup hosts and tournament favorites Brazil suffered their heaviest ever World Cup defeat as they fell 5-0 behind inside 29 minutes on their way to that 7-1 thrashing by the Germans.
Before the Olympic final, Brazil coach Rogerio Micale tried to play down talk of a “revenge” victory.
He pointed out that none of his players were involved in the World Cup semi-final – with the Olympic squads only able to feature three players aged older than 23.
Nevertheless, the capacity crowd created a fantastic atmosphere in the Maracana and got the result they desperately craved.