يَا أَيُّهَا الَّذِينَ آمَنُوا أَطِيعُوا اللَّهَ وَأَطِيعُوا الرَّسُولَ وَأُولِي الْأَمْرِ مِنكُمْ ۖ فَإِن تَنَازَعْتُمْ فِي شَيْءٍ فَرُدُّوهُ إِلَى اللَّهِ وَالرَّسُولِ إِن كُنتُمْ تُؤْمِنُونَ بِاللَّهِ وَالْيَوْمِ الْآخِرِ ۚ ذَٰلِكَ خَيْرٌ وَأَحْسَنُ تَأْوِيلًا
"O you who believe, Obey Allah, Obey his messenger and those in authority from amongst you and if you differ then refer it to Allah and His Messenger if you believe in Allah and the last day" [An-Nisa: 59]
The verse begins with the verb “Atee u” (obey) in the imperative form and the object of obedience is Allah (SWT). The verse then commands “Atee u” (obey) and this time it is referring to the Messenger. The repetition of the word “obey” and the order indicates the two basic reference points that Muslims have the Quran and Sunnah. Therefore, anything in contravention of Quran and Sunnah must be disobeyed and anything from the Quran and Sunnah must be obeyed. This is the principle upon which Muslims are told to live by and this is the principle on which Muslims are instructed to view their rulers. Here the word for rulers or those in authority is ulul amr. The authority is not restricted to the caliph, but also includes the Walis, Wazeers and all those who have authority, especially since the word has been used in the plural.
The ayah does not repeat the verb “Atee u” when it came to the rulers which imply that the ruler must obey Allah and His Messenger in their ruling and authority. For example, the Messenger said:
“There is no obedience to the disobedience of the Creator” [Sahih Bukhari, Volume 9: Hadith 363]
Here there is a prohibition of following an order that goes against the order of Allah (SWT). It is implied that a person can’t obey a ruler who disobeys Allah (SWT). The messenger also said:
"Anyone who dislikes something from his amir should be patient. Anyone who abandons obedience to the amir for even a short time dies the death of the Jahiliyya (ignorance)"
This does not mean their absolute obedience to the rulers. These Hadiths are talking of not rebelling against the rulers due to their misappropriation of the people's rights and not about obeying the rulers in the matters which are a clear violation of the shariah. Rather, when the ruler commands a clear munkar the Muslim must disobey that command and can not say he was following orders.
The Caliph and whoever he appoints possesses authority over you unless they command you to do something which is against the order of Allah which in that case you disobey them. But If they command you to do something which displeases you but is not haram then you must obey him and be patient.