As in, why are they Spanish territory instead of Moroccan?
Long story short:
- Ceuta was conquered by Portugal in 1415, and was "transferred" to Spain in 1640. Melilla was "acquired" in 1497. Other minor places like Vélez de la Gomera was conquered in 1508. So most of these places were conquered during the Age of Discovery, just at the beginning of European colonialism.
- The population of these places are largely of ethnic Spanish descent, although there are also large old minorities of people of Arabs/Berber extraction, Sephardic Jews, and Indians (from India).
- Ceuta was conquered by the Visigoths already in 675, but c. 710 it became the foothold from where the Arab conquest of the Iberian Peninsula was launched.
I can be wrong, but as a Spanish citizen I would say that Spain retains these cities mostly because of their strategic value (cf. Gibraltar), and because there is also some psychological involvement (cf. Serbs and Kosovo).