Did he actually? It's mentioned in several of our texts, but it's a story that was told about him. Without a written testimony from one of them saying, "Yup, we met and Diogenes totally told Alexander off" I don't really see how we can reasonably be more sure. It's possible, even probable (given the quasi-mythology surrounding both Diogenes and Alexander) that our sources are just telling a popular story like all our stories about the things Pythagoras is supposed to have done, but the fact is that the story's recorded in multiple texts. I believe our earliest reference to the story is from Cicero, in the Tusculan Disputations:
at vero Diogenes liberius, ut Cynicus, Alexandro roganti, ut diceret, si quid opus esset, “nunc quidem paululum” inquit “a sole.”
But indeed Diogenes was freer, as a Cynic, he said to Alexander when he asked if he had need of anything, "Sure, get a little out of the sun."
Cicero is of course writing a philosophical treatise, though, not a historical document, so the truth of the anecdote is not entirely certain. Still, he's far from the only source for the tradition, which was quite common in antiquity. Diogenes Laertius says:
ἐν τῷ Κρανείῳ ἡλιουμένῳ αὐτῷ Ἀλέξανδρος ἐπιστάς φησιν, "αἴτησόν με ὃ θέλεις." καὶ ὅς, "ἀποσκότησόν μου," φησί
Alexander stood over him while he was sunning himself in the Cranium [a part of Corinth] and said, "Is there anything you want to ask me?" and he said "Get out of my light."
Plutarch also says more or less the same thing:
ὡς δὲ ἐκεῖνος ἐλάχιστον Ἀλεξάνδρου λόγον ἔχων ἐν τῷ Κρανείῳ σχολὴν ἦγεν, αὐτὸς ἐπορεύετο πρὸς αὐτόν ἔτυχε δὲ κατακείμενος ἐν ἡλίῳ. καὶ μικρὸν μὲν ἀνεκάθισεν, ἀνθρώπων τοσούτων ἐπερχομένων, καὶ διέβλεψεν εἰς τὸν Ἀλέξανδρον. ὡς δὲ ἐκεῖνος ἀσπασάμενος καὶ προσειπὼν αὐτόν ἠρώτησεν εἴ τινος τυγχάνει δεόμενος, ‘μικρὸν’ εἶπεν, ‘ἀπὸ τοῦ ἡλίου μετάστηθι’
As he held the lowest opinion of Alexander he stayed at leisure in the Cranium and Alexander came to him and found him lying in the sun. And he sat up a little when so many men came to him and he stared at Alexander. And when Alexander greeted him and spoke to him and asked whether he wanted anything, he said, "Move a little out of the sun."
The fact that the story has highly philosophical undertones and is quoted either by philosophical writers or writers more interested in philosophy than real history makes it somewhat suspect, but far from impossible. That so many sources quote the exact same story indicates that it was generally accepted in antiquity, which is as close as we're going to get to knowing whether the exchange really happened or is just a fanciful story.