1

通过 MockMvc 运行时传递给 ControllerAdvice 的身份验证令牌为 null 类似,我的 MockMvc 使用 Spring Data REST 和 Spring Security 对 Spring Boot 1.5.16 应用程序进行测试,Authentication无论我手动添加上下文还是使用@WithUserDetails.

这是 Spring Security 测试代码中的错误,还是我在某个地方搞砸了?

这些@RepositoryRestController方法如下所示:

@PostMapping("/resources/{id}/attributes")
public @ResponseBody ResponseEntity<?> attributes(
    @PathVariable("id") long resourceId, 
    @RequestParam(value = "file", required = true) MultipartFile file,
    Authentication authentication ) throws IOException {

    // 2.
    Subject.setAuthentication(authentication);

    try (InputStream input = file.getInputStream()) {
        attributeHandler.read(resourceId, file.getName(), input);
    }

    return ResponseEntity.ok(success());
}

我的 MockMvc 测试看起来像:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
public class RestControllerTest {
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }

    @Test
    @WithUserDetails("myAttributeManagerUsername")
    public void attributes() throws Exception {     

        // 1.
        Authentication authentication = 
            SecurityContextHolder.getContext().getAuthentication();

        mockMvc.perform(
            MockMvcRequestBuilders.fileUpload(
                "/api/resources/1/attributes"
            ).file(attributesFile())
            // 3. .with(authentication(authentication)))
        .andExpect(status().isOk());
    }
}

在测试方法中(在 1.)我已经验证存在身份验证,但是当调用控制器方法时(在 2.)身份验证为空,即使我通过.sessionAttr().with()(如如图所示)。在测试之外运行应用程序时,控制器方法确实会获得一个正确的身份验证令牌(在 2.)和经过身份验证的主题。

有什么想法在我的测试中有什么问题吗?

4

1 回答 1

0

哎呀。这可能不是特别有用,但是...

作为我(未显示)基础架构的一部分,过滤器在触发此错误的 API 之前错误地重置了身份验证。

对噪音感到抱歉。

于 2019-01-23T19:56:15.707 回答