Forward port of https://github.com/spring-projects/spring-security/issues/17898