Je suis en train de développer un simple MVC avec application de sécurité pour l'apprentissage avec Spring Boot. Maintenant, j'écris quelques tests pour les contrôleurs et j'essaie d'accéder aux ressources protégées de Spring Security. Quand je fais ceci sans utilisateur moqué je reçois le code de statut 3xx qui est correct je suppose, parce qu'il me redirige vers le formulaire de connexion. Le facteur reçoit également le code 302 pendant cette requête. Mais lorsque j'essaie d'accéder à la même ressource avec l'annotation @WithMockUser, je reçois également le code de redirection 302. Postman en même temps avec addon intercepteur est de se connecter et de recevoir 200 code de statut qui est correct, je suppose. Ou peut-être qu'il me manque quelque chose, parce que je suis plutôt nouveau avec ce genre de choses? J'apprécierai n'importe quelle aide/explication. Ci-dessous, j'attache mon code de contrôleur, mon config de sécurité et ma classe de test.Pourquoi est-ce que je reçois le code de réponse http de redirection tout en se moquant de l'utilisateur avec Spring Security?
classe test - le second test échoue
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
@ContextConfiguration(classes = {MvcConfig.class, WebSecurityConfig.class})
@WebAppConfiguration
@TestExecutionListeners(listeners = {ServletTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
WithSecurityContextTestExecutionListener.class})
public class WhiproundControllerTest {
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.defaultRequest(get("/"))
.addFilters(springSecurityFilterChain)
.build();
}
@Test
public void shouldRedirectUnauthorizedAccessToLoginForm() throws Exception {
this.mockMvc.perform(get("/whiprounds")).andExpect(status().is3xxRedirection());
}
@Test
@WithMockUser(username = "user", password = "password", roles = "USER")
public void shouldEnterWhiproundsList() throws Exception {
this.mockMvc.perform(get("/whiprounds")).andExpect(status().isOk());
}
}
méthode contrôleur
@RequestMapping(value = "/whiprounds", method = RequestMethod.GET)
public String getAllWhiprounds(WebRequest request, Model model,
@RequestParam(value = "id", required = false) String whiproundId) {
if (whiproundId == null || whiproundId.equals("")) {
model.addAttribute("whiprounds", whiproundRepository.findAll());
return "whiprounds";
}
Whipround whipround = whiproundRepository.findOne(Long.parseLong(whiproundId));
if (whipround == null) {
model.addAttribute("whiprounds", whiproundRepository.findAll());
return "whiprounds";
}
model.addAttribute("whipround", whipround);
double sum = 0.0d;
for (Payment payment : whipround.getPayments()) {
sum += payment.getValue();
System.out.println(payment.toString());
}
model.addAttribute("sum", sum);
model.addAttribute("payment", new Payment());
model.addAttribute("allPayments", whipround.getPayments());
return "singleWhipround";
}
config sécurité
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home", "/login", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().defaultSuccessUrl("/whiprounds", true)
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}