Spring Security疑问:内存认证中withUser方法的来源
withUser() in AuthenticationManagerBuilder Docs (Spring Security 4.2.5) Great question—this is a super common point of confusion with Spring Security 4.x, and I’ve been there myself! Let’s break this down clearly:
The Method Doesn’t Belong to AuthenticationManagerBuilder
You’re not missing anything in the AuthenticationManagerBuilder docs—because withUser() isn’t actually a method on that class. Here’s what’s happening in your code chain:
When you call auth.inMemoryAuthentication(), you’re no longer working with an AuthenticationManagerBuilder instance. That method returns an InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> object, and withUser() is defined on this configurer class (it inherits the method from its parent class UserDetailsManagerConfigurer).
To visualize the chain:
// auth = AuthenticationManagerBuilder instance InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> configurer = auth.inMemoryAuthentication(); UserBuilder userBuilder = configurer.withUser("poef"); // This is where withUser() comes from userBuilder.password("fump").roles("ACTUATOR");
So if you only checked the AuthenticationManagerBuilder docs, you’d never spot withUser()—you need to look up the docs for InMemoryUserDetailsManagerConfigurer instead.
A Critical Note for Your 4.2.5 Setup
One quick heads-up: Spring Security 4.x blocks plain-text passwords by default. Your current code with "fump" as a raw password will throw an error unless you add a password encoder. Here’s how to fix that properly:
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; // ... @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); auth.inMemoryAuthentication() .passwordEncoder(passwordEncoder) .withUser("poef") .password(passwordEncoder.encode("fump")) .roles("ACTUATOR"); }
This ensures your password is hashed and compliant with Spring Security’s security defaults.
内容的提问来源于stack exchange,提问作者user9183621

