【问题标题】:SpringBootTest mock Authentication Principal with a custom User does not work具有自定义用户的 SpringBootTest 模拟身份验证主体不起作用
【发布时间】:2018-03-18 20:04:38
【问题描述】:

我正在使用 Spring Boot 1.4.2,而且我是 Spring Boot 新手。 我有一个身份验证过滤器来设置用户登录时的当前用户信息。 在对控制器的建议中,我调用了获取当前 userId,如下所示:

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;
}

}

一切正常。 但是,过滤器在集成测试中不起作用,我需要模拟当前用户。 我搜索了很多关于如何模拟用户的内容,但没有一个能帮助我。我终于找到了这个可能接近我想要的指南:https://aggarwalarpit.wordpress.com/2017/05/17/mocking-spring-security-context-for-unit-testing/ 以下是我遵循该指南的测试课程:

@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

我已经花了几天的时间,尝试了很多我找到的建议,但仍然失败。我还尝试删除导致错误的行,但是当错误消失后,我仍然无法在控制器建议中获取当前用户信息。

非常感谢任何建议。

UPDATE1:只是想通过对代码进行一些修改来获得我的结果。

根据@glitch 的建议,我更改了代码以在我的测试方法中模拟身份验证和用户,如下所示:

 @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()

【问题讨论】:

  • 试试:when(securityContext.getAuthentication()).thenReturn((Authentication)authentication);
  • 感谢@mangotang 的建议。我试过了,仍然有旧错误:when(securityContext.getAuthentication().getPrincipal()).thenReturn(applicationUser);。你对我还有什么建议吗?

标签: java authentication spring-boot mockito


【解决方案1】:

有一个 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 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()

你只需要对模拟的Authentication设置一个期望,例如:

UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken("aUserName", "aPassword");
Mockito.when(authentication.getPrincipal()).thenReturn(principal);

用上面的代码这一行...

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

... 将返回 UsernamePasswordAuthenticationToken

由于您使用自定义类型(我认为是ApiKeyAuthentication?),您应该让authentication.getPrincipal() 返回该类型而不是UsernamePasswordAuthenticationToken

【讨论】:

  • 感谢@glitch 的建议。我的困难是我有自定义身份验证,即ApiKeyAuthentication。在该自定义身份验证中,我有一个自定义用户AuthenticatedUser。为了添加更复杂的东西,我想要返回的信息是AuthenticatedUser 中的userId。我需要获取的信息发布在我原始帖子的第一个代码部分。我是继续工作的人,所有自定义身份验证内容都是之前创建的。如果您有任何其他建议,我将不胜感激。
【解决方案2】:

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

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

那是因为spring boot测试代码没有和你正在测试的spring boot应用在同一个线程中运行,默认策略是ThreadLocal。使用 MODE_GLOBAL,您可以确保在您的应用程序中实际返回模拟的 SecurityContext 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    相关资源
    最近更新 更多