Cristiano Ronaldo missed a penalty before Portugal conceded an injury-time spot-kick as the European champions set up a last-16 clash with Uruguay.
Ricardo Quaresma curled in a trademark trivela goal on the stroke of half-time at the Mordovia Arena, but Ansarifard's late penalty dropped Portugal to second in Group B behind Spain.
Ronaldo won a second-half spot-kick after a video review but saw his effort saved, with the Real Madrid star unable to add to his four-goal tally at the tournament.
Portugal will face Uruguay in Sochi on July 30 for a place in the quarter-finals after ending IR Iran's hopes of reaching the knockout phase for the first time.
Ronaldo, scorer of all four Portugal goals in his country's first two games, forced IR Iran goalkeeper Ali Beiranvand into an early save after barging his way into the box.
Joao Mario should have put Portugal in front after a defensive mix-up between Saeid Ezatolahi and Beiranvand, but the Inter Milan midfielder blazed over.
IR Iran's first genuine sight of goal came on 34 minutes when Ezatolahi directed a firm header from a free-kick straight into the grateful hands of Rui Patricio.
Quaresma fired Portugal ahead just before the interval when he exchanged passes with Adrien Silva before bending home in style from the edge of the area with the outside of his right foot.
Ronaldo had the chance to double the lead five minutes into the second half after he was upended by Ezatolahi, with a spot-kick awarded following consultation with the video assistant referee (VAR).
But the Portugal captain was denied by Beiranvand who dived to his left to smother Ronaldo's attempt.
Iran coach Carlos Queiroz remonstrated angrily with the officials as Saman Ghoddos appeared to be impeded by William Carvalho inside the area.
There was no VAR intervention on that occasion, but referee Enrique Caceres trotted over to the pitchside monitor after an altercation between Ronaldo and Morteza Pouraliganji.
GROUP B Ladies and Gentlemen.
Not sure about you....but we're off for a lie down. ?#WorldCup #ESPMAR #IRNPOR pic.twitter.com/KiKTGlojZu
— FIFA World Cup (@FIFAWorldCup) June 25, 2018
Ronaldo caught the Iran defender with a forearm across the face, Pouraliganji falling to the ground in a heap as the Portugal forward ultimately escaped with a yellow card.
IR Iran earned a stoppage-time penalty, again with the help of VAR, when Sardar Azmoun's header struck the arm of Cedric after the pair contested a deep cross.
Substitute Ansarifard buried his effort into the roof of the net to set up a dramatic finish.
Mehdi Taremi could have snatched a stunning winner after a deflected shot rolled into his path, but he fired into the side netting as IR Iran fell agonisingly short.
Sources: AFP, FIFA via Getty Images