كتاب الإمارة
33  
The Book on Government
(8)
Chapter: The obligation of obeying leaders in matters that do not involve sin, but it is forbidden to obey them in sinful matters
(8)
باب وُجُوبِ طَاعَةِ الأُمَرَاءِ فِي غَيْرِ مَعْصِيَةٍ وَتَحْرِيمِهَا فِي الْمَعْصِيَةِ ‏‏
Sahih Muslim 1836

It has been narrated on the authority of Abu Huraira that the Messenger of Allah (ﷺ) said:

It is obligatory for you to listen to the ruler and obey him in adversity and prosperity, in pleasure and displeasure, and even when another person is given (rather undue) preference over you.
وَحَدَّثَنَا سَعِيدُ بْنُ مَنْصُورٍ، وَقُتَيْبَةُ بْنُ سَعِيدٍ، كِلاَهُمَا عَنْ يَعْقُوبَ، قَالَ سَعِيدٌ حَدَّثَنَا يَعْقُوبُ بْنُ عَبْدِ الرَّحْمَنِ، عَنْ أَبِي حَازِمٍ، عَنْ أَبِي صَالِحٍ السَّمَّانِ، عَنْ أَبِي هُرَيْرَةَ، قَالَ قَالَ رَسُولُ اللَّهِ صلى الله عليه وسلم ‏ "‏ عَلَيْكَ السَّمْعَ وَالطَّاعَةَ فِي عُسْرِكَ وَيُسْرِكَ وَمَنْشَطِكَ وَمَكْرَهِكَ وَأَثَرَةٍ عَلَيْكَ ‏"‏ ‏.‏
Reference : Sahih Muslim 1836
In-book reference : Book 33, Hadith 52
USC-MSA web (English) reference : Book 20, Hadith 4524
  (deprecated numbering scheme)