Dundee striker David Clarkson scored his eighth goal in eight games to send his club through to the last 16 of the William Hill Scottish Cup.
This thrilling cup tie looked certain to be heading for a replay but the former Scotland front man popped up with a dramatic late winner to continue his incredible scoring streak.
Aberdeen had the first chance of the game with just seconds on the clock as Adam Rooney dragged a shot narrowly wide.
However, it was the home side who stormed into the lead in the fourth minute.
Martin Boyle was fouled on the Dundee right with skipper Kevin Thomson cutely placing the ball for Gary Harkins to take a quick free-kick which Thomas Konrad headed home from six yards.
Aberdeen boss Derek McInnes was looking for a response from his players and he got it on 17 minutes although the goal had more than a slight element of good fortune about it.
With Dundee looking for a foul on Clarkson which never came, the Dons stormed forward and Niall McGinn burst into the home penalty area with his attempted cutback squirming past Bain before hitting off the unfortunate Konrad and into the back of the net.
There was a big penalty shout from the home fans in the 33rd minute when Boyle went down in the Dons box under a combined challenge from goalie Scott Brown and Mark Reynolds but referee Steven McLean was not convinced.
Shortly after, Greg Stewart pounced on a mistake by Aberdeen’s Shay Logan with the Dundee striker calmly taking a touch but then he blasted his shot well over.
Aberdeen then came close to taking the lead when Rooney headed a David Goodwillie cross goalward but Bain pulled off an outstanding stop to foil the Dons striker and ensure the sides went in at half-time level.
Chances were at a premium as the second 45 began with both sides cancelling one another out.
However, Bain had to look lively to keep out a rasping 25-yard drive from Ryan Jack with McGinn heading straight at the keeper from the resultant corner.
With the game poised on a knife edge, there was a distinct sense of nervousness about a lot of the play from both sides.
Aberdeen looked the more likely to score though and hit the side netting twice through Rooney and then Goodwillie shortly before the 80-minute mark.
With just 60 seconds of normal time remaining, Bain came to the rescue once again saving a fierce free-kick from Hayes.
However, right on 90 minutes, James McPake pushed up front and headed the ball into the path of Clarkson who kept his cool to stab home past Brown to the delight of the home fans.
However, Aberdeen came mighty close to scoring an incredible equaliser in the third minute of injury time, when McGinn hit a shot which Bain amazingly saved, pushing the ball onto the underside of his cross bar before it bounced to safety.