The narrative begins in Persia, introducing two brothers of contrasting fortunes: the wealthy Qasim and the humble woodcutter, Ali Baba. The turning point of the story occurs when Ali Baba, while working in the forest, witnesses a band of "forty horsemen" approaching a "great rock." By overhearing the leader command the rock to "Open sesame!", Ali Baba gains access to a hidden chamber filled with "beautiful carpets, rolls of silk and piles of gold and jewels." This discovery serves as the catalyst for the ensuing conflict, as Ali Baba’s newfound wealth draws the unwanted attention of his brother, Qasim.
Qasim, driven by envy and curiosity, forces Ali Baba to reveal the location of the treasure. Upon entering the cave, Qasim’s greed proves to be his undoing. Overwhelmed by the abundance of riches, he suffers a lapse in memory, forgetting the magical command. In his panic, he shouts "Open barley!" and other incorrect phrases, which leaves him "trapped inside." When the thieves return, they discover his presence and "did away with him," marking the first major casualty caused by the misuse of the secret entrance.
The core of the story shifts from the discovery of wealth to a battle of wits between the thieves and Ali Baba’s wife, Morgiana. The leader of the thieves, recognizing that someone else knows their secret, attempts to track down the perpetrator. He marks Ali Baba’s door with "white chalk" to identify the target for a midnight raid. However, Morgiana’s keen observation allows her to counter this move; she marks "all the other doors in the town," creating a state of confusion that thwarts the thieves' initial assassination attempt.
The leader’s second attempt involves a more sophisticated infiltration. He disguises himself as an "oil merchant" and hides his "thirty-nine thieves" within large jars loaded onto mules. When he seeks refuge in Ali Baba’s home, Morgiana’s vigilance once again saves the day. Upon hearing a voice from the jars asking, "Is it time?", she realizes the danger and assumes the authority of the leader to keep them contained.
Her decisive actions—pouring "poison into a glass of wine" for the leader and revealing the "dagger he had hidden" under his coat—demonstrate her role as the true protector of the household. Ali Baba, initially angry at her interference, soon realizes her "wise" nature. The story concludes with the couple living "happily after this," having secured their safety and their future through the cleverness of a woman who proved far more capable than the thieves who underestimated her.