Needing only a draw to progress to the finals, Stuart Baxter’s side took a 50th minute lead through striker Percy Tau.
However, Ahmad Benali converted a penalty in the 66th minute to give South African fans an anxious closing 24 minutes of play.
Tau eased their fears, however, with his second of the match in the 69th minute as Bafana held on to secure a famous 2-1 victory.
When all was said and done, Bafana qualified second behind Nigeria in Group E and will take their place in the newly expanded 24-team tournament to be played in Egypt between 21 June and 19 July.
CAF will conduct a draw for finals on 12 April.