Facebook Inc. FB 2.12% said hackers gained access to nearly 50 million accounts in what amounts to the largest-ever security breach at the social network at a time when it is working to regain the trust of its more than 2 billion users.

The company said Friday it didn’t know who was behind the attack, which was discovered earlier this week. Hackers could have gained access to the accounts as early as July 2017, the company said.

Chief Executive Mark Zuckerberg said Facebook didn’t have evidence the attackers had accessed people’s private messages and posts, or posted as those users. But he didn’t rule out that possibility. “The investigation is still very early so we do not yet know if any of the accounts were actually misused,” he said. “This, of course, may change.”

Mr. Zuckerberg and Chief Operating Officer Sheryl Sandberg were among those affected by the breach, Facebook said.

Executives said the attack was sophisticated, requiring the hackers to find and exploit three obscure flaws in its code. They said it would be difficult to determine who was behind it. “And we may never know,” said Guy Rosen, Facebook’s executive in charge of safety and security.

Facebook said Friday that it was still investigating the scope of the breach. Security researchers warned that it could ultimately have a much wider impact.

The breach is the latest setback for the world’s largest social network, which has been criticized by Congress for its mishandling of a two-year Russian influence operation on its platform. In March, the company said that the data of millions of users were improperly shared with Cambridge Analytica, the now-defunct analytics firm that had ties to President Trump’s 2016 campaign.

The revelation comes months after Facebook overhauled its security team and eliminated the role of chief security officer. The news also comes little more than a month before the 2018 midterm elections, a period during which Facebook will be under intense scrutiny to safeguard its platform from foreign meddling.

Facebook shares dropped 2.6% Friday to close at $164.46.

Facebook said it was working with the Federal Bureau of Investigation to determine the identities of the hackers. “The FBI has been in contact with Facebook, and we are aware of the situation. We decline to provide further details at this time,” a FBI representative said.

Facebook said all users who were believed to be affected by the breach were automatically logged out of their account late Thursday night Pacific Time and asked to log in again. Users that weren’t logged out of their account aren’t believed to have been affected. Facebook also said there would be a notification at the top of affected users’ news feeds that would appear after they logged back in to their accounts.

Hackers gained access to the accounts by exploiting a vulnerability in Facebook’s “view as” feature, which lets people see how their profiles appear to others. Three bugs in Facebook’s code connected to the feature let outsiders steal access tokens—digital keys that keep people logged into Facebook. One of the bugs appeared in a Facebook tool urging users to upload a video wishing one another happy birthday, executives said.

With the stolen tokens in hand, Facebook said, hackers could then take over accounts, impersonating users and accessing private information about those people and their friends, including a user’s Facebook connections, friends’ posts and messages. Facebook executives said there was no evidence that this happened, nor that users’ passwords and credit-card information were exposed.

Still, the breach gave hackers access to information that could be used in identity theft, said Dan Kaminsky, chief scientist with security vendor White Ops Inc. The hackers also could have sold the tokens themselves, he said.

Facebook’s authentication tokens can be used to log in to websites outside of Facebook itself, Mr. Kaminsky said, through the “Log In With Facebook” feature used by sites such as Tinder and Spotify. A Facebook spokesman said this was technically possible but Facebook didn’t have evidence that it occurred. Some affected users have been logged out of third-party apps as a precaution, the spokesman said.

Related Video Tech-company executives at The Wall Street Journal's D.Live conference in Hong Kong responded to concerns over data security in the wake of Facebook's privacy scandal. (Originally published April 20, 2018)

The spokesman said Facebook has never had a security breach as large. The company reset the access tokens for the nearly 50 million affected accounts, as well as an additional 40 million subject to a “view as” lookup in the past year.

Facebook said it is turning off the “view as” feature as it conducts a security review. The fact that the bug has been exploited by hackers makes the breach a “more serious matter,” than other security incidents, Mr. Kaminsky said. “Many times we discover bugs and no one’s found them yet,” he said. “That’s not the case in this instance.”

The revelation Friday capped a difficult week for Facebook.

Monday, the two co-founders of its popular Instagram app abruptly resigned after they clashed with Mr. Zuckerberg over the app’s autonomy. Similar issues led the co-founders of Facebook’s WhatsApp to depart.

In Washington on Friday, the breach prompted a request for more information by Rohit Chopra, a Democratic commissioner on the Federal Trade Commission, as well as a call for social-media legislation from Sen. Mark Warner (D., Va.)

A Senate committee this week heard testimony about data privacy from several tech companies, including Alphabet Inc.’s Google and Twitter Inc. Facebook didn’t attend.

Facebook’s ability to police its data has been called into question. Besides the improper sharing of data of about 87 million people with Cambridge Analytica, Facebook said earlier this year that most people using the social network could have had information scraped by marketers who used a feature that distributed profile data connected to email addresses and phone numbers.

—Dustin Volz

contributed to this article.

Write to Deepa Seetharaman at Deepa.Seetharaman@wsj.com and Robert McMillan at Robert.Mcmillan@wsj.com