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