We know that hearing and obeying is due to the Muslim rulers, as revealed in the verse that says: {O you who believe, obey Allah and obey the Messenger, and those of you who are in authority.} [Surat an-Nisā’: 59] And the Prophet (may Allah’s peace and blessings be upon him) said: "Hearing and obeying is a right, unless a sin is commanded; if a sin is commanded, there must be no hearing or obeying." [Narrated by Al-Bukhāri (2955) and Muslim (1839)]
‘Ubādah ibn as-Sāmit (may Allah be pleased with him) reported: "We pledged to the Messenger of Allah (may Allah’s peace and blessings be upon him) to hear and obey both in times of hardship and ease, when we felt energetic and when we felt tired, and when others are preferred over us; that we would not dispute with those in authority; and that we would speak the truth wherever we may be, not fearing the blame of blamers, for the sake of Allah." [Narrated by Al-Bukhāri (7055) and Muslim (1709)]
Abu Zur‘ah (may Allah have mercy upon him) said: "And we fulfill the duty of jihad and Hajj with the Muslim rulers at every time and era, and we do not uphold revolt against the rulers or engaging in turmoil. We hear and obey those whom Allah put in charge of us, and we do not depart from obedience to them; we adhere to the Sunnah and the Muslim Group." [Sharh Usūl I‘tiqād Ahl As-Sunnah Wa Al-Jamā‘ah, by Imām Al-Lālakā’i (1/175)]
Obedience to the rulers is only due in what is good; yet if a sin is involved, such obedience is prohibited, as indicated by the above-mentioned Hadīth by Ibn ‘Umar (may Allah be pleased with him): "... unless a sin is commanded; if a sin is commanded, there must be no hearing or obeying." In another Hadīth, the Prophet (may Allah’s peace and blessings be upon him) said: "There must be no obedience in a sin; obedience is only due in what is good." [Narrated by Al-Bukhāri (7257) and Muslim (1840)]
Imām Abu Ibrāhīm al-Muzani said: "Obedience to the rulers is due in what is pleasing to Allah Almighty and when displeasing things to Him are avoided. We should refrain from revolting against them when they transgress and act unjustly and should repent to Allah Almighty so that He make them relent to their subjects." [Sharh As-Sunnah, by Al-Muzani (84)]