我做了一个非常简单的演示应用程序来尝试测试Spring安全性。
这是我的应用程序配置
@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实现接受所有具有密码‘密码’的用户,将管理角色授予' 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中的配置()方法是否被调用。我做错了什么?
发布于 2015-05-04 22:26:09
authenticationManagerBean()的Per WebSecurityConfigurerAdapter api参考
重写此方法以将AuthenticationManager从配置程序(AuthenticationManagerBuilder)公开为Bean。
因此,只需在您的authenticationManagerBean()中重写WebSecurityConfigurerAdapter,并将其公开为@Bean的bean。
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}https://stackoverflow.com/questions/30036065
复制相似问题