Apple recently changed their authentication methods which now use Trusted Devices and a much longer code sent to those trusted devices instead of a traditional 2FA text message. This may have something to do with it, but i have seen a few other posts mention the inability to add the 2FA code when in Recovery Mode for the older installers. I have not seen or heard of any work around.
Try booting into Recovery Mode using Command + Option + R which theoretically will not tie the OS to the AppleID so it should not require an AppleID to authenticate in order to download the OS.
If you are not using Recovery Mode and are trying to download macOS through the App Store, then you can instead download macOS 10.10 or better yet 10.11 as those installers are available outside of the App Store.
How to download macOS - Apple Support
I highly recommend you create a bootable macOS 10.11 USB installer now while you can since this can only be done on a compatible Mac.
Create a bootable installer for macOS - Apple Support
FYI, a 2012 iMac can run up to macOS 10.15 Catalina although Catalina does not support 32 bit apps. Installing macOS 10.13+ will update the iMac's firmware to allow access to the online macOS installers through Internet Recovery Mode. There is a chance you may need to upgrade to both 10.11 and 10.13 before being able to upgrade to 10.15.
Make sure to have a good backup before doing anything else just in case something goes wrong.