You can’t. Castling is blocked while your king is attacked, and also when the square it crosses or the square it lands on is attacked1. It’s gone for good once your king has moved, and with any rook that has moved. Being in check earlier in the game doesn’t cost you the right, and a rook under attack can still castle2.
Why people argue about it
New players ask this all the time, and the answers usually turn up a second myth: that a rook under attack can’t castle3,4. Only the king’s path matters, so on the queenside the rook can pass over an attacked square.
Once per game, you can castle while your king is in check. You still can't castle through or onto an attacked square, and the rook you castled with can't move on your next turn.
When someone is still learning, an illegal castling attempt is just pointed out. They take it back and can play any move they like, with no touch-move penalty.
Check lands and a new player reaches for the rook to castle away. Your table needs 2 calls: does an illegal castle get a free take-back while someone is learning, and is castling out of check ever allowed? Castling coach points out the mistake and lets the player choose any move, no touch-move penalty. Panic castle allows it once a game, never through or onto an attacked square, and that rook stays put next turn. For teaching games, our pick is Castling coach.
Play it a different way? Post it so others can vote on it.