To compound Hamilton's frustration, a five-place grid penalty for a gearbox change on Friday meant he starts Sunday's race from ninth.
It is Ferrari's first pole in Bahrain since Felipe Massa topped the timesheets in 2008 and ended a stranglehold over qualifying for the race by Mercedes-GP.
Sebastian Vettel produced a flying last lap in qualifying Saturday to take pole for Sunday's Bahrain Grand Prix.
Haas, who turned heads with their speed in the Australian season opener, could not quite repeat their dream qualifying result from Melbourne with Magnussen's teammate Romain Grosjean failing to make it past the opening 18 minutes of qualifying.
Vettel snatched an opportunistic win from Hamilton in Formula One's season opener in Australia two weeks ago, taking advantage of a timely virtual safety auto to pit and stay ahead of the Briton who had led from pole.
"I was very happy that I got the second run and I got it clean", Vettel said.
The two Ferraris were the only ones to dip into the one minute 29 second bracket, with Valtteri Bottas half a second off Raikkonen's benchmark with what was reigning champions Mercedes' best effort.
The German, the victor of the season-opener in Melbourne, will be joined on the front row by his Ferrari teammate Kimi Raikkonen.
"We need to wait", said Vettel.
"Not ideal - far from ideal in the last run with the traffic", said Raikkonen, the 2007 champion. Given that Vettel does not feel 100% comfortable with his Ferrari, it could be Kimi Raikkonen who could add to his record seven podiums in Bahrain.
Only one of the past five races in Bahrain have been won by the driver in pole position, with Hamilton the last driver to win from pole in 2015.
A major surprise for Toro Rosso as Pierre Gasly made it through and Brendon Hartley was only nine hundredths of a second of 10th.