In June 2017, President Donald Trump nominated Spencer to serve as the 76th United States Secretary of the Navy. Spencer was confirmed by the United States Senate on August 1, 2017. He was sworn in on August 3, 2017, and served until November 24, 2019. On July 15, 2019, he assumed the duties of acting Secretary of Defense and expected "to continue to serve in this role until a Secretary of Defense nominee is confirmed by the Senate and assumes office. At that time, I will continue to serve as Secretary of the Navy." He assumed the duties of Deputy Secretary of Defense on July 23, 2019. In November 2019, Secretary of Defense Mark Esper stated that he had learned that Spencer had proposed to White House officials that, if they did not interfere with military justice proceedings against Navy SEAL Eddie Gallagher, Spencer would ensure that Gallagher was able to retire with his Trident Pin, a symbol of membership in the SEALs. Gallagher had been convicted by court martial in July 2019 of wrongfully posing for an unofficial picture with a human casualty, and acquitted of six additional charges including murder. Spencer's private proposal to the White House – which he did not share with Esper over the course of several conversations about the matter – contradicted his public position on the Gallagher case, chief Pentagon spokesman Jonathan Hoffman said in a statement. Esper fired Spencer on November 24, 2019, saying he was "flabbergasted" by Spencer going directly to the White House outside the chain of command. The next day Esper told reporters that Trump had issued an order that Gallagher be allowed to retire as a Navy SEAL. In a letter to Trump acknowledging his termination, Spencer stressed his belief in the importance of "good order and discipline", saying, "Unfortunately, it has become apparent that... I no longer share the same understanding with the Commander in Chief who appointed me, in regards to the key principle of good order and discipline. I cannot in good conscience obey an order that I believe violates the sacred oath I took in the presence of my family, my flag and my faith to support and defend the Constitution of the United States." On November 27, 2019, The Washington Post published an op-ed by Spencer, in which he said that Trump "has very little understanding of what it means to be in the military", and referred to Trump's actions in the Gallagher case as a "shocking and unprecedented intervention".
Later career
On February 7, 2020, Spencer endorsed Michael Bloomberg for U.S. President in the 2020 U.S. presidential election.