In imaging and focusing applications, spherical aberration induces axial broadening of the point spread function (PSF). A transparent medium between lens and object of interest induces spherical aberration. We propose a method that first obtains both the physical thickness and the refractive index of the aberration inducing medium in situ by measuring the induced focal shifts for paraxial and large angle rays. Then, the fourth order angle dependence of the optical path difference inside the medium is used to correct the spherical aberration using a phase-only spatial light modulator. The obtained measurement accuracy of 3% is sufficient for a complete compensation as demonstrated in a model microscope with NA 0.3 with glass plate induced axial broadening of the PSF by a factor of 5.