كتاب الإمارة
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 1709 h

It has been narrated on the authority of Junida b. Abu Umayya who said:

We called upon 'Ubada b. Samit who was ill and said to him: May God give you health I Narrate to us a tradition which God may prove beneficial (to us) and which you have heard from the Messenger of Allah (ﷺ). He said: The Messenger of Allah (ﷺ) called us and we took the oath of allegiance to him. Among the injunctions he made binding upon us was: Listening and obedience (to the Amir) in our pleasure and displeasure, in our adversity and prosperity, even when somebody is given preference over us, and without disputing the delegation of powers to a man duly invested with them (Obedience shall be accorded to him in all circumstances) except when you have clear signs of his disbelief in (or disobedience to) God-signs that could be used as a conscientious justification (for non-compliance with his orders).
حَدَّثَنَا أَحْمَدُ بْنُ عَبْدِ الرَّحْمَنِ بْنِ وَهْبِ بْنِ مُسْلِمٍ، حَدَّثَنَا عَمِّي عَبْدُ اللَّهِ بْنُ وَهْبٍ، حَدَّثَنَا عَمْرُو بْنُ الْحَارِثِ، حَدَّثَنِي بُكَيْرٌ، عَنْ بُسْرِ بْنِ سَعِيدٍ، عَنْ جُنَادَةَ بْنِ أَبِي أُمَيَّةَ، قَالَ دَخَلْنَا عَلَى عُبَادَةَ بْنِ الصَّامِتِ وَهُوَ مَرِيضٌ فَقُلْنَا حَدِّثْنَا أَصْلَحَكَ اللَّهُ، بِحَدِيثٍ يَنْفَعُ اللَّهُ بِهِ سَمِعْتَهُ مِنْ، رَسُولِ اللَّهِ صلى الله عليه وسلم ‏.‏ فَقَالَ دَعَانَا رَسُولُ اللَّهِ صلى الله عليه وسلم فَبَايَعْنَاهُ فَكَانَ فِيمَا أَخَذَ عَلَيْنَا أَنْ بَايَعَنَا عَلَى السَّمْعِ وَالطَّاعَةِ فِي مَنْشَطِنَا وَمَكْرَهِنَا وَعُسْرِنَا وَيُسْرِنَا وَأَثَرَةٍ عَلَيْنَا وَأَنْ لاَ نُنَازِعَ الأَمْرَ أَهْلَهُ قَالَ ‏ "‏ إِلاَّ أَنْ تَرَوْا كُفْرًا بَوَاحًا عِنْدَكُمْ مِنَ اللَّهِ فِيهِ بُرْهَانٌ ‏"‏ ‏.‏
Reference : Sahih Muslim 1709h
In-book reference : Book 33, Hadith 69
USC-MSA web (English) reference : Book 20, Hadith 4541
  (deprecated numbering scheme)