Spain was competing in just its second semifinal, while the Brazilians will miss out on the final for the first time in eight years.
Defending world champion Russia also earned a spot in the gold medal match with a 5-3 win over Tahiti in the other semifinal.
Bruno Xavier opened the scoring for Brazil, but the Spaniards replied in the second period with Juanma's strong finish.
Spain withstood a barrage of Brazilian chances in the later stages of the match, but the former prevailed in extra time when captain Nico rescued his squad with two minutes, 32 seconds remaining and found the back of the net for the deciding goal.
Catch the final between Russia and Spain right after the bronze medal match featuring Brazil and Tahiti late Sunday night on CBC (11 p.m.-1 a.m. local in Windsor and Saskatchewan, 11:30 p.m.-1:30 a.m. local in the Maritimes, Manitoba and North, 12 a.m.-2 a.m. local in Newfoundland, Ontario, Quebec, Alberta and B.C.).