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

标签 java authentication spring-boot mockito

我正在使用 Spring Boot 1.4.2,我是 Spring Boot 的新手。 我有一个身份验证过滤器,用于在用户登录时设置当前用户信息。 在给 Controller 的建议中,我调用了以下方法来获取当前的 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

我已经在这上面花了几天时间,尝试了很多我发现的建议,但仍然失败了。我也尝试删除导致错误的行,但是当错误消失后,我仍然无法在我的 Controller 建议中获取当前用户信息。

非常感谢任何建议。

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 有值(value)。但是当我跳转到 Controller 建议中的代码时,下面的 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 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 的这次更新:

I now can get rid of the error in the testing class. I debugged into the code, see that the securityContext has value when I am in the testing class. But when I jump to the code inside the controller advice, the below get returns 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.

关于java - 具有自定义用户的 SpringBootTest 模拟身份验证主体不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46615504/

相关文章:

java - 以最小的空间复杂度查找数组中最大整数的总和

java - 如何在 Linux 环境中提供 java 文件的 XML 路径

java - 将 Class<?> cls 作为方法参数传递?

c# - C# 中的 Grpc 中间件或拦截器

java - 具有 MultiPartFile 属性的 Restful POST API DTO 的 Spring 启动测试

java - JTextField 上的回调函数

javascript - 获取访问 token 和登录时出现 Azure AD 错误

.net - ASP.NET MVC 中的用户身份验证和授权

java - spring boot jdbc 连接

spring-boot - 使用 spring-boot-sleuth 将跟踪发送到 Datadog