![](/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.