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

It has been narrated on the authority of Abu 'Abd al-Rahman from 'Ali that the Messenger of Allah (ﷺ) sent a force (on a mission) and appointed over them a man. He kindled a fire and said:

Enter it. Some people made up their minds to enter it (the fire), (carrying out the order of their commander), but the others said: We fled from the fire (that's why we have come into the fold of Islam). The matter was reported to the Messenger of Allah (ﷺ). He said to those who Contemplated entering (the fire at the order of their commander): If you had entered it, you would have remained there until the Day of Judgment. He commanded the act of the latter group and said: There is no submission in matters involving God's disobedience or displeasure. Submission is obligatory only in what is good (and reasonable).
حَدَّثَنَا مُحَمَّدُ بْنُ الْمُثَنَّى، وَابْنُ، بَشَّارٍ - وَاللَّفْظُ لاِبْنِ الْمُثَنَّى - قَالاَ حَدَّثَنَا مُحَمَّدُ، بْنُ جَعْفَرٍ حَدَّثَنَا شُعْبَةُ، عَنْ زُبَيْدٍ، عَنْ سَعْدِ بْنِ عُبَيْدَةَ، عَنْ أَبِي عَبْدِ الرَّحْمَنِ، عَنْ عَلِيٍّ، أَنَّعليه وسلم بَعَثَ جَيْشًا وَأَمَّرَ عَلَيْهِمْ رَجُلاً فَأَوْقَدَ نَارًا وَقَالَ ادْخُلُوهَا ‏.‏ فَأَرَادَ نَاسٌ أَنْ يَدْخُلُوهَا وَقَالَ الآخَرُونَ إِنَّا قَدْ فَرَرْنَا مِنْهَا ‏.‏ فَذُكِرَ ذَلِكَ لِرَسُولِ اللَّهِ صلى الله عليه وسلم فَقَالَ لِلَّذِينَ أَرَادُوا أَنْ يَدْخُلُوهَا ‏"‏ لَوْ دَخَلْتُمُوهَا لَمْ تَزَالُوا فِيهَا إِلَى يَوْمِ الْقِيَامَةِ ‏"‏ ‏.‏ وَقَالَ لِلآخَرِينَ قَوْلاً حَسَنًا وَقَالَ ‏"‏ لاَ طَاعَةَ فِي مَعْصِيَةِ اللَّهِ إِنَّمَا الطَّاعَةُ فِي الْمَعْرُوفِ ‏"‏ ‏.‏
Reference : Sahih Muslim 1840a
In-book reference : Book 33, Hadith 63
USC-MSA web (English) reference : Book 20, Hadith 4535
  (deprecated numbering scheme)