KABUL—An Islamic State militant stormed a Sikh temple in the heart of Kabul, killing 25 worshipers and taking dozens of people hostage in a prolonged siege that once again exposed the ability of insurgents to carry out attacks in the Afghan capital.

Dozens of Sikh worshipers were gathering for morning prayers on Wednesday when a gunman stormed the temple, according to the Interior Ministry. Men, women and children scrambled out of the compound as the attacker moved through the temple. An Afghan security official initially...