我做了一个非常简单的演示应用程序来尝试测试 Spring Boot 安全性。
这是我的应用程序配置
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplication
public class DemoApplication extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityService securityService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(securityService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated();
http.httpBasic();
http.csrf().disable();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
我的 UserDetailsService 实现接受所有密码为“password”的用户,将管理员角色授予“admin”用户。
@Service
public class SecurityService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Collection<GrantedAuthority> authorities;
if (username.equals("admin")) {
authorities = Arrays.asList(() -> "ROLE_ADMIN", () -> "ROLE_BASIC");
} else {
authorities = Arrays.asList(() -> "ROLE_BASIC");
}
return new User(username, "password", authorities);
}
}
最后我创建了一个简单的测试来检查它:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoApplicationTests {
@Autowired
private AuthenticationManager authenticationManager;
@Test
public void thatAuthManagerUsesMyService() {
Authentication auth = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken("admin", "password")
);
assertTrue(auth.isAuthenticated());
}
}
我希望测试通过,但我得到了 BadCredentialsException。调试后发现测试中Spring注入的AuthenticationManager不是我配置的。在 Eclipse 调试器中挖掘对象时,我看到 UserDetailsServer 是一个 InMemoryUserDetailsManager。
我还检查了 DemoApplication 中的 configure() 方法是否被调用。我究竟做错了什么?