The Prophet ﷺ said, "Whoever obeys me has obeyed Allah, and whoever disobeys me has disobeyed Allah. Whoever obeys the ruler has obeyed me, and whoever disobeys the ruler has disobeyed me."
عن النبي ﷺ قال: من أطاعني فقد أطاع الله، ومن يعصني فقد عصى الله، ومن يطع الأمير فقد أطاعني، ومن يعص الأمير فقد عصاني.
Bukhari narrated it in the Book of Jihad and Expeditions (2957), and Muslim narrated it in the Book of Leadership (1835:32), both of them through Abu Zinad, from Araj, from Abu Hurairah, who mentioned it. The wording given here is Muslim's.