Spring Security测试期间的空身份验证

时间:2016-05-08 15:18:35

标签: java spring spring-security spring-test-mvc

我想集成测试Spring安全身份验证。只是登录工作。但在测试期间出现了以下错误:

java.lang.AssertionError: Authentication should not be null

我的自定义UserDetailsS​​ervice只是从数据库中获取用户并将其映射到我的自定义UserDetails。我在这做错了什么?这就是我所拥有的:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Application.class})
@WebAppConfiguration
public class SecurityConfigTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity())
            .build();
    }
    @Test
    public void shouldAuthenticate() throws Exception {
        mockMvc
            .perform(formLogin())
            .andExpect(authenticated());
    }
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic()
            .and()
            .authorizeRequests()
                .antMatchers("/", "/login").permitAll()
            .and()
            .csrf().disable();
    }
}
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer{
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

1 个答案:

答案 0 :(得分:2)

正如Spring Security Reference ManualmockMvc.perform(formLogin())

中所述
  

将使用用户名“user”,密码“password”和有效的CSRF令牌向“/ login”提交POST。

因此,如果您的登录网址不是/login,用户名不是user,或密码不是password,那么您不应期望它能够正常运行。< / p>

要为数据库中实际存在的用户提供用户名/密码组合,您应该能够使用mockMvc.perform(formLogin("/auth").user("admin").password("pass"))(假设登录URL为/auth,用户名为{{1}密码为admin)。

查看参考手册以获取更多详细信息和示例。