We investigate coupling of localized spins in a semiconductor quantum dot embedded in a microcavity with a finite quality factor. The lowest cavity mode and the quantum dot exciton are coupled forming a polariton, whereas excitons interact with localized spins via exchange. The finite quality of the cavity Q is incorporated in the model Hamiltonian by adding an imaginary part to the photon frequency. The Hamiltonian, which treats photons, spins and excitons quantum mechanically, is solved exactly. Results for a single polariton clearly demonstrate the existence of a resonance, sharper as the temperature decreases, that shows up as an abrupt change between ferromagnetic and antiferromagnetic indirect anisotropic exchange interaction between localized spins. The origin of this spin-switching finite-quality-factor effect is discussed in detail remarking on its dependence on model parameters, i.e., light-matter coupling, exchange interaction between impurities, detuning and quality factor. For parameters corresponding to the case of a (Cd,Mn)Te quantum dot, the resonance shows up for Q ≈ 70 and detuning around 10 meV. In addition, we show that, for such a quantum dot, and the best cavities actually available (quality factors better than 200) the exchange interaction is scarcely affected.