Spring Security Test和MockMvc向REST控制器提供空的自定义UserDetails参数


问题内容

我正在尝试编写一个集成测试,该测试可以到达REST端点并获取特定身份验证用户的数据(我在测试中设置的那个)。我最初尝试使用进行安装mockMvc =webAppContextSetup(wac).apply(springSecurity()).build(),但始终失败BeanInstantiationException。在使用自定义UserDetails实现测试SpringSecurity和MvcMock的帮助下,我能够通过设置setUp来解决该问题。现在,我已将设置切换为使用standaloneSetup,现在可以调用控制器了。但是,无论我做什么,我都无法将在测试中创建的自定义UserDetails对象放入对MockMvc的调用最终在其控制器中的方法中。

我正在使用Spring 4.2.2和Spring Security 4.0.1。

我的测试代码如下所示:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { RestControllerITConfig.class })
@WebAppConfiguration
public class ControllerIT {

  private MockMvc mockMvc;

  @Before
  public void setUp() {
    mockMvc = standaloneSetup(new Controller())
                .setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver())
                .build();
  }

  @Test
  public void testGetEndpoint() throws Exception {
    CustomUserDetails userDetails = new CustomUserDetails("John","Smith", "abc123");
    assertNotNull(userDetails);
    MvcResult result = mockMvc.perform(
      get("/somepath").with(user(userDetails)))    
      .andExpect(status().isOk())
      .andExpect(content().contentType("text/json")));
  }
}

@Configuration
@ComponentScan(basePackageClasses = { AuthenticationConfig.class })
public class RestControllerITConfig {
}

@Configuration
@EnableWebSecurity
@ComponentScan("com.my.authentication.package")
public class AuthenticationConfig extends WebSecurityConfigurerAdapter {
  // snip
}

@Target({ ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface MyUser {
}

@RestController
@RequestMapping("/somepath")
public class Controller {

  @RequestMapping(value = "", method = RequestMethod.GET)
  public ResponseEntity<Object> getSomePath(@MyUser CustomUserDetails customUser) {
    customUser.getName(); // <== Causes NPE
  }
}

为了简洁起见,省略了其他不相关的配置。我真的不明白为什么我在测试中显式创建的自定义UserDetails对象没有传递到我的REST控制器中,而是一个空对象。我在这里做错了什么?有没有人有类似案例的可行例子?提前谢谢了。


问题答案:

通过将AuthenticationConfig的过滤器显式添加到,我终于可以使它正常工作StandaloneMockMvcBuilder。所以我的设置现在看起来像:

private MockMvc mockMvc;
@Autowired
private MyController controller;
@Autowired
private AuthenticationConfig authConfig;

@Before
public void setUp() {
  mockMvc = standaloneSetup(controller)
              .setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver())
              .addFilters(authConfig.getCustomFilter())
              .build();
}