Java 具有自定义用户的SpringBootTest模拟身份验证主体不起作用

Java 具有自定义用户的SpringBootTest模拟身份验证主体不起作用,java,authentication,spring-boot,mockito,Java,Authentication,Spring Boot,Mockito,我使用的是Spring Boot 1.4.2,我是Spring Boot的新手。 我有一个身份验证过滤器,用于在用户登录时设置当前用户信息。 在给控制器的建议中,我打电话获取当前用户ID,如下所示: public static String getCurrentUserToken(){ return ((AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).get

我使用的是Spring Boot 1.4.2,我是Spring Boot的新手。 我有一个身份验证过滤器,用于在用户登录时设置当前用户信息。 在给控制器的建议中,我打电话获取当前用户ID,如下所示:

public static String getCurrentUserToken(){
    return ((AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
}
这是我的自定义AuthenticatedUser:

public class AuthenticatedUser implements Serializable {

private final String userName;
private final String userId;
private final String sessionId;

public AuthenticatedUser(String userName, String userId, String sessionId) {
    super();
    this.userName = userName;
    this.userId = userId;
    this.sessionId = sessionId;
}

public String getUserName() {
    return userName;
}

public String getUserId() {
    return userId;
}

public String getSessionId() {
    return sessionId;
}
}

一切正常。 但是,过滤器在集成测试中不起作用,我需要模拟当前用户。 我搜索了很多关于如何模仿用户的内容,但没有一个能帮到我。我终于找到了这本指南,它很可能接近我想要的: 以下是我的测试课程,遵循该指南:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class PersonalLoanPreApprovalTest {

@Before
public void initDB() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testRequestPersonalLoanPreApproval_Me() {
  AuthenticatedUser applicationUser = new 
  AuthenticatedUser("test@abc.com", "2d1b5ae3", "123");
  UsernamePasswordAuthenticationToken authentication = new ApiKeyAuthentication(applicationUser);
  SecurityContext securityContext = mock(SecurityContext.class);

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

  // error at this line
  when(securityContext.getAuthentication().getPrincipal()) .thenReturn(applicationUser); 

  // The controller for this api has the advice to get the userId
  MyResponse response = restTemplate.getForObject(url.toString(), MyResponse.class);
}
}
我得到了这个错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
AuthenticatedUser cannot be returned by getAuthentication()
getAuthentication() should return Authentication
我已经为此花了几天时间,尝试了很多建议,但还是失败了。我还试图删除导致错误的行,但当错误消失后,我仍然无法在控制器建议中获取当前用户信息

非常感谢您的任何建议

更新1:只是想在代码中修改一下结果

使用@glitch suggestion,我将代码更改为模拟我的测试方法中的身份验证和用户,如下所示:

 @Test
 public void testRequestPersonalLoanPreApproval_Me() {
    AuthenticatedUser applicationUser = new AuthenticatedUser("testtu_free@cs.com", "2d1b5ae3-cf04-44f5-9493-f0518cab4554", "123");
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(applicationUser);      

  // The controller for this api has the advice to get the userId
  MyResponse response = restTemplate.getForObject(url.toString(), MyResponse.class);
}
}
我现在可以消除测试类中的错误。我在代码中进行了调试,在测试类中查看securityContext是否有值。但当我跳转到控制器建议中的代码时,下面的get返回null:

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

有一个Spring测试注释(
org.springframework.security.test.context.support.WithMockUser
)可以为您实现这一点

@Test
@WithMockUser(username = "myUser", roles = { "myAuthority" })
public void aTest(){
    // any usage of `Authentication` in this test invocation will get an instance with the user name "myUser" and a granted authority "myAuthority"
    // ...
}
或者,您可以通过模拟Spring的
身份验证
继续当前的方法。例如,在您的测试用例中:

Authentication authentication = Mockito.mock(Authentication.class);
然后告诉Spring的
SecurityContextHolder
存储此
Authentication
实例:

SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(securityContext);
现在,如果您的代码需要
Authentication
返回某些内容(可能是用户名),您只需以通常的方式对模拟的
Authentication
实例设置一些期望值,例如

Mockito.when(authentication.getName()).thenReturn("aName");
这与您已经在做的非常接近,但您只是模仿了错误的类型

更新1:针对OP的此更新:

我现在可以消除测试类中的错误。我在代码中进行了调试,在测试类中查看securityContext是否有值。但当我跳转到控制器建议中的代码时,下面的get返回null:

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

您只需要对模拟的
身份验证设置期望值,例如:

UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken("aUserName", "aPassword");
Mockito.when(authentication.getPrincipal()).thenReturn(principal);
使用上面的代码,这一行

SecurityContextHolder.getContext().getAuthentication().getPrincipal();
。。。将返回该
UsernamePasswordAuthenticationToken


既然您使用自定义类型(
ApiKeyAuthentication
,我想?),那么您应该让
authentication.getPrincipal()
返回该类型,而不是
UsernamePasswordAuthenticationToken

除了glytching的答案之外,在模拟时我还必须添加以下行:

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

这是因为spring引导测试代码与正在测试的spring引导应用程序不在同一线程中运行,默认策略是ThreadLocal。使用MODE_GLOBAL,您可以确保模拟的SecurityContext对象在应用程序中实际返回。

尝试:
when(SecurityContext.getAuthentication())。然后返回((身份验证)身份验证)谢谢@mangotang的建议。我尝试了它,但在以下行仍然存在旧错误:
when(securityContext.getAuthentication().getPrincipal())。然后返回(applicationUser)。你还有其他建议吗?谢谢@glitch的建议。我的困难在于我有自定义身份验证,即
ApiKeyAuthentication
。在自定义身份验证中,我有一个自定义用户
AuthenticatedUser
。要添加更复杂的内容,我想获取的信息是
AuthenticatedUser
中的
userId
。我需要得到的信息发布在我原来帖子的第一个代码部分。我是那个继续工作的人,所有自定义身份验证都是以前创建的。如果您还有其他建议,我将不胜感激。