KABUL, Afghanistan — Militants disguised as shepherds who were tending a flock of sheep attacked a Shiite mosque in Kabul on Friday as worshipers were leaving, killing five people and wounding at least 20 others, officials said.

At least one of the attackers set off the explosives he was carrying when he was confronted by security guards, and he was also killed in the explosion. It was not immediately clear how many militants were involved in the attack, but the police arrested three suspects at the scene.

The Islamic State claimed responsibility for the attack, hours after the Taliban denied that they were involved.

Several recent attacks have struck Shiite places of worship, and the Islamic State has claimed responsibility for many of them. Kabul and other major Afghan cities are on high alert ahead of Ashura, an annual Shiite commemoration of the martyrdom of Prophet Muhammad’s grandson.