The basic security measure to protect IP in STM32 is the FLASH Readout Protection (RDP). This is activated by programming a certain pattern into the Option Bytes, and has three levels. Level 0 is no protection, this is the default setting. Level 2 is a "total" protection with no way to revert, disabling the debugging interfaces entirely, which also implies that there is no way to erase and reprogram the device using usual programming facilities (the program running from internal FLASH still can erase and reprogram other portions of FLASH, so it is possible e.g. to write a custom bootloader for RDP Level2).
RDP Level 1 is a tradeoff setting, which still allows reprogramming, but only if the RDP Level is changed to Level 0 before that. While performing this change, the hardware erases the entire FLASH content. This is expected, as this protects the content of FLASH from IP theft.
Content of backup registers (RTC_BKPxR/TAMP_BKPxR) is also automatically erased, as they are intended to hold key material and are protected by the RDP mechanism, too.
However, it may come as a surprise, that content of the VBAT-powered backup-SRAM in STM32 models, where such backup-SRAM is implemented ('F2/'F4/'F7/'H7/'H5), is erased at this moment, too. This too is a protection mechanism, as users may want to store sensitive data in the backup-SRAM.