“The two ranger vehicles had pretended that they were coming back from operations at some front line. They were all covered in dust,” Mr. Azimi said. “When they reached the gates of the army corps, they started firing and one of them got off the vehicle and blew himself up.”

The attack came weeks after militants entered the Afghan Army’s main hospital in Kabul, the capital, and killed more than 50 people in a siege that lasted nearly seven hours. The Islamic State claimed responsibility for that assault. In that attack, too, security officials said, the militants had inside help.

While the group has been getting attention in recent days because of the American military’s use of its largest conventional bomb against an Islamic State cave complex in eastern Afghanistan, the Taliban remain the biggest security threat to the country. The group has expanded its territory over the past couple years and threatens several cities.

Such a major security breach in Balkh, even before the start of the insurgents’ spring offensive, is a major concern to Afghan forces who are already struggling in the fight against the Taliban. In 2016, more than 6,700 Afghan forces were killed in battle.

Analysts and officials with the American-led coalition forces, who are training and assisting the Afghan forces, have been very critical of the inept leadership and widespread corruption in the ranks, which is contributing to the large number of casualties. Gen. John W. Nicholson, the commander of the American and NATO forces here, has expressed his need for a few thousand more American troops on the group to assist and train the Afghan forces.

Analysts said the repeated ability of a few militants to cause tremendous bloodshed in highly secure areas was an especially troubling sign ahead of the Taliban’s spring offensive. Jawed Kohistani, an Afghan security analyst, said the Balkh attack seemed to be in retaliation for Afghan special forces’ going on the offensive in recent weeks and targeting local Taliban leaders in night raids. Daring attacks like the one on Friday, he said, are possible because of infiltrators and the Taliban’s careful study of the Afghan security forces and their weaknesses.

“You know the attack was carried out on Friday, which is a national holiday, in the afternoon, which is the time of Friday Prayer,” Mr. Kohistani said. “On Friday, the military preparation of soldiers for responding to possible attack is decreased, the checking of the personnel also decreases and the enemy was aware of that.”

“The gap, weakness and problem is in management, in the intelligence agency and the carelessness of high-ranking officials,” he added.