A pulsating match saw the hosts take an early lead, quickly fall 3-1 behind before half-time and then mount a stunning second-half comeback.
However, Thierry Henry’s side could not see the job through as Spain substitute Sergio Camello kept calm in the most tense of situations to score twice in the extra period.
Both goals sparked jubilant celebrations among the Spanish, who mobbed Rayo Vallecano forward Camello as they won Olympic gold for the first time since 1992.
The thrilling triumph continued Spain’s success, little over a month after they won the men’s European Championship, beating England in the final.
They also won the men’s under-19 European title last month, while the women’s team lifted the World Cup last year.
In contrast, the mood of the hosts was one of deflation as Henry consoled his players.
With France unable to clinch victory, Great Britain remained fifth in the Paris 2024 medal table.
Both nations have won 14 gold medals.