Azhar struck his fifth test century and featured in two crucial partnerships with captain Misbah-ul-Haq (68 not out) and Sarfraz Ahmed (48) as Pakistan chased down a 302-run victory target in 57.3 overs. (Agencies)
Azhar, 28, eventually fell after a 137-ball 103 which contained six fours, leaving Pakistan needing seven runs for victory.
Misbah completed the formality, scoring the winning run off Shaminda Eranga and the clean-shaven Pakistan captain celebrated by twirling an invisible moustache.
"We were 1-0 down in the series, so we had no other option. Everybody felt we should have a go at it," said Misbah, calling the win a farewell gift for departing coach Dav Whatmore.
Chasing what appeared an improbable victory target from 59 overs, Pakistan got off to a flying start with openers Khurram Manzoor (21) and Ahmed Shehzad (21) adding 35 quick runs before both fell to Suranga Lakmal in their pursuit of quick runs.
Azhar and Younus Khan (29) showed the same urgency as they maintained a four-plus run rate before Younus pulled Angelo Mathews to midwicket to leave Pakistan at 97 for three.
Azhar then added 89 brisk runs from 14.5 overs with Sarfraz Ahmed, whose 46-ball cameo included four boundaries and a six off Rangana Herath.
Eranga denied Sarfraz a half-century but Azhar raised 109 runs with Misbah for the fifth wicket to take Pakistan to the verge of a memorable victory.
Earlier, Sri Lanka added 81 runs to their overnight score of 133-5 before folding in their second innings.
Spinners Abdur Rehman (4-56) and Saeed Ajmal (3-53) ran through the Sri Lankan bottom half to bowl them out for 214. Paceman Mohammad Talha claimed 3-65.
Azhar struck his fifth test century and featured in two crucial partnerships with captain Misbah-ul-Haq (68 not out) and Sarfraz Ahmed (48) as Pakistan chased down a 302-run victory target in 57.3 overs.