The 'law for the protection of athletes' health and the fight against doping' will come into effect within 20 days and meets recommendations made by the World Anti-Doping Agency (WADA).
"It strengthens the Madrid 2020 bid," Spain's secretary of state for sport, Miguel Cardenal, said in parliament.
"Doping is no longer on the agenda as a concern for Madrid's candidacy. It is a determined step forward for Spain in the fight against those who do not respect the purity of sport.
"This law is the final link and the end of a process of adaptation to WADA (norms)."
The new law strengthens existing legislation with an increase in amounts available for fines and introduces the possibility of life bans.
"It is something that has been called for internationally, and brings our laws into line with the latest modifications in the world anti-doping code," ruling Popular Party member Antonio Roman said.
"(Not having the law) had a negative effect on the Madrid 2016 candidacy and it should not return to happen again with Madrid 2020 or the Barcelona bid for the Winter Games of 2022."
The law will see the creation of a new body to replace the Spanish anti-doping agency (AEA).
The Spanish Agency for the Protection of Health in Sport will be an independent organisation responsible for managing and carrying out doping tests around the clock.
It will also administer punishments nationally, raise fines and be able to suspend licences.
Spain hopes the new law will help to dispel the impression that it is soft on doping.
Last month, the conclusion of the Operation Puerto trial into an alleged doping ring in cycling drew widespread international condemnation.
The judge in charge of the case ordered evidence, including bags of blood seized by police in raids, to be destroyed, depriving WADA and other sports bodies of the chance to analyse them.
The Spanish doctor at the centre of the trial, Eufemiano Fuentes, had told the court that as well as cyclists his clients included athletes in soccer, athletics, tennis and boxing.
Madrid is bidding against Istanbul and Tokyo for the 2020 Games, with the International Olympic Committee (IOC) due to elect the winning city in September.
- Sports & Recreation