Numbers 25:17

Vex the Midianites, and smite them:

The command to vex and smite the Midianites belongs to Israel's national apostasy at Baal-peor, when the people joined in idolatrous worship and provoked God's wrath. In that Baal-peor account it shows that God distinguishes between those who disobey Him and those who remain faithful to Him. The command to harass and strike came from Christ, Israel's invisible leader, speaking through Moses, from the One who can create and can destroy.

It was not given until the Midianites filled up the measure of their iniquities, when their day of probation ended and the door of mercy was closed to them. God had long spared idolatrous Moab and Midian in infinite mercy and had forbidden war against them because their cup of iniquity was not yet full. During that sparing He gave them evidence upon evidence and clear distinct light that the mighty Jehovah was the God to serve. When the king of Moab called Balaam to curse Israel for reward, God controlled the corrupt prophet and compelled him to pronounce rich blessing on Israel as God's chosen under almighty protection, shining a last ray of light on a stiff-necked people defying God.

The command then went forth as just divine judgment because, at Balaam's suggestion, the Midianites harassed Israel with deceitful wiles and schemes. They laid a snare that lured Israel to break God's commandments through idolatry and fornication, drew Israel into sin and disobedience, and brought death on many thousands, so their iniquity became full.