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

It has been narrated on the authority of 'All who said:

The Mersenger of Allah (ﷺ) sent an expeditionand appointed over the Mujahids a man from the Ansar. (While making the appointment), he ordered that his work should be listened to and obeyed. They made him angry in a matter. He said: Collect for me dry wood. They collected it for him. Then he said: Kindle a fire. They kindled (the fire). Then he said: Didn't the Messenger of Allah (ﷺ) order you to listen to me and obey (my orders)? They said: Yes. He said: Enter the fire. The narrator says: (At this), they began to look at one another and said: We fled from the fire to (find refuge with) the Messenger of Allah (ﷺ) (and now you order us to enter it). They stood quiet until his anger cooled down and the fire went out. When they returned, they related the incident to the Messenger of Allah (ﷺ). He said: If they had entered it, they would not have come out. Obedience (to the commander) is obligatory only in what is good.
وَحَدَّثَنَا مُحَمَّدُ بْنُ عَبْدِ اللَّهِ بْنِ نُمَيْرٍ، وَزُهَيْرُ بْنُ حَرْبٍ، وَأَبُو سَعِيدٍ الأَشَجُّ - وَتَقَارَبُوا فِي اللَّفْظِ - قَالُوا حَدَّثَنَا وَكِيعٌ، حَدَّثَنَا الأَعْمَشُ، عَنْ سَعْدِ بْنِ عُبَيْدَةَ، عَنْ أَبِي عَبْدِ الرَّحْمَنِ، عَنْ عَلِيٍّ، قَالَ بَعَثَ رَسُولُ اللَّهِ صلى الله عليه وسلم سَرِيَّةً وَاسْتَعْمَلَ عَلَيْهِمْ رَجُلاً مِنَ الأَنْصَارِ وَأَمَرَهُمْ أَنْ يَسْمَعُوا لَهُ وَيُطِيعُوا فَأَغْضَبُوهُ فِي شَىْءٍ فَقَالَ اجْمَعُوا لِي حَطَبًا ‏.‏ فَجَمَعُوا لَهُ ثُمَّ قَالَ أَوْقِدُوا نَارًا ‏.‏ فَأَوْقَدُوا ثُمَّ قَالَ أَلَمْ يَأْمُرْكُمْ رَسُولُ اللَّهِ صلى الله عليه وسلم أَنْ تَسْمَعُوا لِي وَتُطِيعُوا قَالُوا بَلَى ‏.‏ قَالَ فَادْخُلُوهَا ‏.‏ قَالَ فَنَظَرَ بَعْضُهُمْ إِلَى بَعْضٍ فَقَالُوا إِنَّمَا فَرَرْنَا إِلَى رَسُولِ اللَّهِ صلى الله عليه وسلم مِنَ النَّارِ ‏.‏ فَكَانُوا كَذَلِكَ وَسَكَنَ غَضَبُهُ وَطُفِئَتِ النَّارُ فَلَمَّا رَجَعُوا ذَكَرُوا ذَلِكَ لِلنَّبِيِّ صلى الله عليه وسلم فَقَالَ ‏ "‏ لَوْ دَخَلُوهَا مَا خَرَجُوا مِنْهَا إِنَّمَا الطَّاعَةُ فِي الْمَعْرُوفِ ‏"‏ ‏.‏
Reference : Sahih Muslim 1840b
In-book reference : Book 33, Hadith 64
USC-MSA web (English) reference : Book 20, Hadith 4536
  (deprecated numbering scheme)