Richarlison drove home at the second attempt in the seventh minute and headed Brazil into a 2-0 lead before completing his hat-trick with a fine strike in the 30th minute with the German defence in chaos.
Nadiem Amiri pulled one back for Germany after the break and although Max Arnold was dismissed in the 63rd minute, a Ragnar Ache header gave Brazil an unexpectedly nervous the final stages.
But with Germany pushing forward, Brazil caught them on the break in stoppage time, Paulinho finishing off a counter-attack with a fine shot into the top corner.