The Messenger of Allah ﷺ said, "When the imam says, 'Allah hears whoever praises Him,' say, 'Our Lord, to You belongs all praise.' Whoever's words coincide with the words of the angels will have his past sins forgiven."
أخبرنا قتيبة عن مالك عن سمي عن أبي صالح
أن رسول الله ﷺ قال إذا قال الإمام سمع الله لمن حمده فقولوا ربنا ولك الحمد فإن من وافق قوله قول الملائكة غفر له ما تقدم من ذنبه
Muslim narrated it in the Book of Prayer, chapter on saying "sami Allahu liman hamidah" and "hamdan" and "ameen," hadith no. 409, from Qutayba. Bukhari narrated it in the Book of Adhan, chapter on the merit of saying, "O Allah, our Lord, to You belongs all praise," hadith no. 796, from the hadith of Malik with the same wording. It is also found in Muwatta (Yahya), 1/88, and in Kubra, hadith no. 650.