Most of the time when you dream, everything seems completely normal. But when you wake up, you remember that you don't live in a castle, your auntie isn't actually a horse and you can't really play the bongos...annoyingly. You don't usually know you're dreaming while you're in the middle of a dream. But some people are able to not only realise they are dreaming, halfway through the dream, but control it and enjoy the dream on their own terms, this is called lucid dreaming.
Nobody knows for definite what is happening when you get a lucid dream but the most likely explanation is the following: When you enter sleep, certain parts of your brain get switched off, usually the parts involved with common sense and logic. But in some people (or in people who practice) it's possible to keep one part of the brain active: The Dorsolateral Prefrontal Cortex (DLPFC)
The DLPFC is a part of the brain involved with long-term memory. It helps you remember where your house is, how to write and what your friends names are. If this part of the brain is activated (rather than switched off) it can sometimes notice something in the dream doesn't match real memories. It will suddenly go "wait a moment, this isn't what the world is really like, I remember the real world" and your brain realises that what you're thinking about is fake; a dream.