Forward port of https://github.com/spring-projects/spring-security/issues/17797 to 6.5.x