It depends what country the flight is taking place in and what country the airline belongs to.
After Twin Towers many countries made it illegal for any but specific, authorised personnel to be on a flight deck during flight.
Some countries take this more seriously than others, the rules in UK being particularly draconian.