代码之家  ›  专栏  ›  技术社区  ›  Jan Nielsen

@respositoryRestController中的@withUserDetails为空的身份验证

  •  1
  • Jan Nielsen  · 技术社区  · 6 年前

    类似 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),其中包含经过认证的主题。

    你知道我的考试有什么问题吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jan Nielsen    6 年前

    向右。这不太可能特别有帮助,但是…

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

    对不起,噪音太大了。

    推荐文章