President Obama, in a rare rebuke to Muslim leaders, told the UN General Assembly Tuesday that hate speech “tolerated” in mosques helped give rise to the “mindless medieval menace” of ISIS.

Speaking of the Middle East, he said “much of the collapse in order has been fueled because leaders sought legitimacy, not because of policies or programs, but by resorting to persecuting political opposition or demonizing other religious sects, by narrowing the public space to the mosque, where in too many places perversions of a great faith were tolerated,” said Obama.

“And these forces built up for years, and are now at work helping to fuel both Syria’s tragic civil war and the mindless medieval menace of ISIL,” he added, using another name of the terror group.

Obama also took a victory lap at the UN meeting — praising himself for a bevy of accomplishments in his last address as president to the international body and to knock Donald Trump.

“Let me recount the progress we have made these past eight years,” Obama told the assembled international leaders, recounting the financial and economic recovery, the Iran nuclear deal, renewed US diplomatic relations with Cuba, among other successes.

“The world is by many measures less violent and more prosperous than ever before,” he said.

“We need to acknowledge these achievements in order to summon the confidence to carry this effort forward, and make sure we do not abandon the very things that have delivered this progress.”

Obama steps down as president on January 20, 2017.

The president appeared to use the international forum to get in indirect attacks on Trump.

Obama railed against “a crude populism … which seeks to restore what they believe was a better simpler age free of outside contamination,” saying that “I do not believe those visions can deliver security over the long-term.”

Trump is running on a largely populist message to replace Obama.

In another instance, Obama took a swipe at Trump’s signature position — building a wall on the US border with Mexico.

“Today, a nation ringed by walls would only imprison itself,” he said, calling for openness and global cooperation to defeat challenges like Zika.

“We cannot combat a disease like Zika that recognizes no borders. Mosquitoes do not respect walls,” he said.