类似
Authentication token passed to ControllerAdvice is null when running through MockMvc
,我对SpringBoot1.5.16应用程序的mockmvc测试使用了SpringDataRest和SpringSecurity,但始终为空。
Authentication
参数是手动添加上下文还是使用
@WithUserDetails
.
这是SpringSecurity测试代码中的一个bug,还是我搞砸了什么地方?
这个
@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.)时,身份验证为空,即使我手动设置上下文(在3.)通过
.sessionAttr()
或
.with()
(如图所示)。当在测试之外运行应用程序时,控制器方法确实会获得一个适当的认证令牌(位于2),其中包含经过认证的主题。
你知道我的考试有什么问题吗?