In the original story of Ali Baba and the Forty Thieves, Ali Baba learns about the thieves’ treasure store when he actually overhears the thieves getting into their cave. He hears the phrase to open the cave - which is where we get the phrase “open sesame” - and the phrase to close it, “close sesame.”
However, depending on the version and the adaptation, this scene has been retold in numerous ways. Most try to stay close to the actual scene because it’s not all that scary (especially when the retelling is targeting kids).
Other ways Ali Baba has been shown finding out about the cave includes befriending a thief, bringing a thief out of the book (“Inkheart” did this, and is the only one to do so), and overhearing the phrase but not seeing the cave to start.