How gender can be used legally

Can gender (sex) ever be used legally as a required qualification for a job? If not, why? Is so, when (example)?