Younès Belhanda and Medhi Benatia squandered close-range chances in a penalty box before Iran finally countered after 20 minutes, only for Karim Ansarifard to scuff his shot when clean through on goal.
[10] Diego Costa then twisted and turned away from two Portugal defenders to score with a low shot to the left corner which brought the two sides level.
As the clock ticked down, however, Gerard Piqué brought down Ronaldo just outside the box, with the Portugal star completing the scoring and his hat-trick with a free-kick into the top right corner of the net.
[15] João Moutinho swung in a cross from the right after a short corner and Cristiano Ronaldo headed the ball powerfully past goalkeeper Munir Mohamedi from six yards out and into the middle of the goal to open the scoring in the 4th minute.
Ronaldo shot over the crossbar when Bernardo Silva's mishit presented him with a shooting chance on the edge of the box early in the second half.
Rui Patrício then made a save to preserve Portugal's lead when Hakim Ziyech's free-kick was headed towards goal by Younès Belhanda, the goalkeeper diving to palm the ball away from danger.
In the 54th minute, Diego Costa picked up Andrés Iniesta's pass inside the area and saw Ramin Rezaeian's attempted clearance ricochet off his leg and past Beiranvand low into the left corner of the net.
Saeid Ezatolahi pulled Iran level shortly after the hour but his close-range finish after a scramble was ruled out courtesy of VAR after Rezaeian was found in an offside position.
Mehdi Taremi's back-post header fizzed over De Gea's crossbar seven minutes from time as Iran pushed for an equaliser, but Spain held on for a 1–0 win.
Iran then managed to get a penalty in stoppage time after referee used VAR to determine that Cédric's handball from Sardar Azmoun's header had been intentional, which Karim Ansarifard converted high to his right.
[15] In the 14th minute, a mix-up between Sergio Ramos and Andrés Iniesta allowed Khalid Boutaïb to steal possession on the halfway line, burst through on goal and finish through the legs of David de Gea.
Nordin Amrabat, Manuel da Costa and Mbark Boussoufa were all booked in three-minute period before Sergio Busquets headed over the crossbar from Isco's corner.
And when Iago Aspas turned home Dani Carvajal's cross from the right after a short corner – the goal given by VAR after a long delay – Spain was tied in the first minute of added time.