Madara received the rinnegan at the time he was close to the point of death.
How did madara get his rinnegan. Nagato was chosen to get madara's eyes because his clan (uzumaki) was a distant branch of the senju. A tablet that was altered by the way, by the black zetsu. After sasuke overused his eyes towards blindness by battling 5 kage and danzo in the land of iron, obito implanted itachi’s eyes to sasuke.
Then he surgically attached the flesh onto his. The reason why nagato got two rinnegan is because of how madara was able to develop the eye itself. Manga, naruto / by double lasers.
This led to madara gaining the rinnegan in his old age. After spitting the flesh he bit off from hashirama, he implanted it — and the chakra that comes with it — on himself. Near the end of his natural life, he awoke the rinnegan in both eyes.
The 2nd time, he died after entrusting everything in obito’s hand, he died. Although edo tensei madara can use them to absorb ninjutsu, he can't use it to summon the gedo mazo, or use limbo. So, in total madara died 3 times.
How did sasuke get his rinnegan. Before he dies, he only awakens one rinnegan. It's kinda the same with nagato's rinnegan or itachi's.
He had deciphered part of the tablet left behind by the sage of six paths. Nagato got the rinnegan from madara, who implanted the eyes into him. As said earlier, there is no way for a member of the uzumaki clan to gain.