A divided U.S. Supreme Court said government employees have a constitutional right not to pay union fees in a ruling that affects 5 million workers and deals a heavy blow to the labor movement.

The 5-4 decision overturns a 1977 Supreme Court ruling that had let public-sector unions collect so-called agency fees from non-members to help cover the cost of collective bargaining. The court’s newest member, Neil Gorsuch, joined his conservative colleagues in the majority.

Writing for the court an Illinois case, Justice Samuel Alito said mandatory fees violated the free speech rights of workers who disagree with the union’s...