【问题标题】:Why am I receiving redirect http response code while mocking user with Spring Security?为什么我在使用 Spring Security 模拟用户时收到重定向 http 响应代码?
【发布时间】:2017-09-19 11:24:45
【问题描述】:

我正在开发一个带有安全应用程序的简单 MVC,用于使用 Spring Boot 进行学习。现在我正在为控制器编写一些测试,并且我正在尝试访问受 Spring Security 保护的资源。当我在没有模拟用户的情况下执行此操作时,我收到状态代码 3xx,我想这是正确的,因为它会将我重定向到登录表单。 Postman 在此请求期间也收到 302 代码。但是,当我尝试使用 @WithMockUser 注释访问相同的资源时,我也会收到 302 重定向代码。 Postman 与拦截器插件同时登录并接收 200 状态码,我想这是正确的。或者也许我错过了一些东西,因为我对这些东西很陌生?我将不胜感激任何帮助/解释。 下面我附上我的控制器代码、安全配置和测试类。

测试类 - 第二个测试失败

@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());
    }
}

控制器方法

@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";
    }

安全配置

@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());
    }
}

【问题讨论】:

    标签: java spring unit-testing spring-mvc spring-security


    【解决方案1】:

    问题解决了。在构建我的 MockMvc 对象时,我忘记应用 Spring Security。 Test 类中的 setup 方法应如下所示:

     @Before
        public void setup() {
            mockMvc = MockMvcBuilders
                    .webAppContextSetup(context)
                    .defaultRequest(get("/"))
                    .addFilters(springSecurityFilterChain)
                    .apply(springSecurity())
                    .build();
        }
    

    【讨论】:

      猜你喜欢
      • 2015-08-25
      • 2015-12-22
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      相关资源
      最近更新 更多