The Torah tells the encounter briefly: Potiphar's wife caught Joseph by his cloak, and he fled. The midrash, unwilling to leave so fierce a struggle so thinly described, puts Psalms on Joseph's lips — verses he could not yet have known, since David had not yet been born. That is part of the point. A righteous man, the sages are saying, already knows in his bones the words a king will later write.
The wife of Potiphar began gently, coaxing him with loving words. He would not. She threatened him next: "I will shut you up in prison." Joseph answered, anticipating the Psalm by centuries: "The Lord looses the prisoners" (Psalms 146:7).
She escalated. "I will bow you down with distress; I will blind your eyes." Joseph answered with the next verse: "The Lord opens the eyes of the blind and raises them that are bowed down" (Psalms 146:8).
At last she tried a bribe — a thousand talents of silver if he would comply. Joseph refused that too.
The sages are teaching that temptation climbs a ladder: sweet words first, then fear, then money. A person who does not have an answer ready at each rung gets pulled over. Joseph had the Psalms in his mouth before the Psalms had been written, because a tzaddik's answer is older than any one king's composition.
(From the 1901 Hebraic Literature anthology, drawing on Yoma 35b.)