模拟 SecurityContextHolder / Authentication 总是返回 null

Man*_*pez 5 spring spring-security spring-test junit4 mockito

我知道这个问题经常被问到,但也许我有一些特别的事情。我正在尝试对支持 REST(不是 Spring MVC)的 Spring Boot 应用程序进行一些集成测试,并且由于某种原因SecurityContextHolder.getContext().getAuthentication()总是返回 null,即使在@WithMockUser测试中使用也是如此。我不确定这是否与在配置类上使用配置文件有关,但到目前为止我们还没有遇到任何问题。

班级

@Override
public ResponseEntity<EmployeeDTO> meGet() {
    Principal principal = SecurityContextHolder.getContext().getAuthentication();
    logger.debug("Endpoint called: me({})", principal);
    EmployeeDTO result;

    // Get user email from security context
    String email = principal.getName(); // NPE here

// ...
}
Run Code Online (Sandbox Code Playgroud)

测试

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        properties = {"eureka.client.enabled:false"})
@WithMockUser
@ActiveProfiles(value = "test")
public class MeControllerTest extends IntegrationSpringBootTest {

@Autowired
private TestRestTemplate restTemplate;

@MockBean
private SecurityContext securityContext;

@MockBean
private Authentication authentication;

@MockBean
private EmployeeRepository employeeRepository;

@BeforeClass
public static void setUp() {

}

@Before
@Override
public void resetMocks() {
    reset(employeeRepository);
}

@Test
public void meGet() throws Exception {
    when(securityContext.getAuthentication()).thenReturn(authentication);
    securityContext.setAuthentication(authentication);
    when(authentication.getPrincipal()).thenReturn(mockEmployee());
    SecurityContextHolder.setContext(securityContext);
    when(employeeRepository.findByEmail(anyString())).thenReturn(mockEmployee());

    ResponseEntity<EmployeeDTO> employeeDTOResponseEntity =
            this.restTemplate.getForEntity("/me", EmployeeDTO.class);
// ...
}
Run Code Online (Sandbox Code Playgroud)

如果我返回一个模拟Principal而不是mockEmployee()测试甚至无法启动,因为发生这种情况:

org.springframework.beans.factory.BeanCreationException: Could not inject field: private org.springframework.security.core.Authentication com.gft.employee.controller.MeControllerTest.authentication; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'org.springframework.security.core.Authentication#0' is expected to be of type 'org.springframework.security.core.Authentication' but was actually of type '$java.security.Principal$$EnhancerByMockitoWithCGLIB$$657040e6'
Run Code Online (Sandbox Code Playgroud)

附加说明:此 Spring Boot 应用程序也使用 OAuth2 进行授权,但必须将其关闭以进行这些测试。这就是我们使用配置文件的原因。省略@ActiveProfiles注释会给我们一个针对端点请求的 401 Unauthorized 错误。

可以使用 PowerMock,但如果可能的话,我想避免使用它。

小智 6

为身份验证 SecurityContextHolder 编写 Junit 的更简单方法是模拟它们。以下是它的工作实现。您可以根据需要添加模拟类,然后设置 SecurityContextHolder 的上下文,然后使用 when() 进一步模拟并返回适当的模拟值。

    AccessToken mockAccessToken = mock(AccessToken.class);
    Authentication authentication = mock(Authentication.class);
    SecurityContext securityContext = mock(SecurityContext.class);

    when(securityContext.getAuthentication()).thenReturn(authentication);

    SecurityContextHolder.setContext(securityContext);

    when(SecurityContextHolder.getContext().getAuthentication().getDetails()).thenReturn(mockSimpleUserObject);
Run Code Online (Sandbox Code Playgroud)


Man*_*pez 1

MockMvc尽管该应用程序不是基于 Spring MVC,但我最终还是使用了它。此外,我将SecurityContext调用分离到另一个服务中,但在此之前我可以断言注释@WithMockUser工作正常。

其工作的关键是在类级别使用这些片段:

@WebMvcTest(MeController.class)
@Import({ControllerConfiguration.class, BeanConfiguration.class})
public class MeControllerTest {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

使用@WebMvcTest使得不必SecurityContext首先初始化 a 变得容易。您甚至不必打电话springSecurity()。您可以像mockMvc.perform()往常一样进行操作,对 的任何调用都SecurityContext将返回您指定的任何模拟用户,或者使用@WithMockUser或模拟处理此类调用的服务。