![](/img/trans.png)
[英]How to eliminate @Configuration classes with security enabled in Spring Boot unit testing
[英]Testing Spring Boot Security configuration
我已经做了一个非常简单的演示应用程序来尝试测试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()方法是否被调用。 我究竟做错了什么?
每个WebSecurityConfigurerAdapter api的authenticationManagerBean() 参考
重写此方法以将configure(AuthenticationManagerBuilder)中的AuthenticationManager公开为Bean。
所以只要覆盖authenticationManagerBean()
在你的WebSecurityConfigurerAdapter并将其作为一个bean @Bean
。
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.