The origin of the spin-axis orientations (obliquities) of the giant planets is a fundamental issue because if the obliquities resulted from tangential collisions with primordial Earth-sized protoplanets, then they are related to the masses of the largest planetesimals out of which the planets form1-7. A problem with this mechanism, however, is that the orbital planes of regular satellites would probably be uncorrelated with the obliquities, contrary to observations6,7. Alternatively, they could have come from an external twist that affected the orientation of the Solar System plane2; but in this model, the outer planets must have formed too rapidly, before the event that produced the twist8. Moreover, the model cannot be quantitatively tested. Here I show that the present obliquities of the giant planets were probably achieved when Jupiter and Saturn crossed the 1:2 orbital resonance9during a specific migration process: different migration scenarios cannot account for the large observed obliquities. The existence of the regular satellites of the giant planets does not represent a problem in this model because, although they formed soon after the planetary formation, they can follow the slow evolution of the equatorial plane it produces.