Sal*_*Sal 4 java authentication mockito spring-boot
我正在使用Spring Boot 1.4.2,并且是Spring Boot的新手。我有一个身份验证筛选器,用于在用户登录时设置当前用户信息。在控制器的建议中,我进行了调用以获取当前userId,如下所示:
public static String getCurrentUserToken(){
return ((AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUserId();
}
Run Code Online (Sandbox Code Playgroud)
这是我的自定义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;
}
Run Code Online (Sandbox Code Playgroud)
}
一切正常。但是,该筛选器在集成测试中不起作用,我需要模拟当前用户。我搜索了很多关于如何模拟用户的内容,但没有一个对我有帮助。我终于找到了可能与我想要的指南接近的指南: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);
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
AuthenticatedUser cannot be returned by getAuthentication()
getAuthentication() should return Authentication
Run Code Online (Sandbox Code Playgroud)
我已经花了几天时间,尝试了很多发现的建议,但仍然失败了。我也尝试删除导致错误的行,但是当错误消失后,我仍然无法在控制器建议中获得当前的用户信息。
任何建议都将受到高度赞赏。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我现在可以摆脱测试类中的错误。我调试了代码,在测试类中看到securityContext具有价值。但是,当我跳到控制器建议中的代码时,以下get返回null:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
Run Code Online (Sandbox Code Playgroud)
有一个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"
// ...
}
Run Code Online (Sandbox Code Playgroud)
另外,您可以通过模拟Spring的方法继续当前的方法Authentication。例如,在您的测试用例中:
Authentication authentication = Mockito.mock(Authentication.class);
Run Code Online (Sandbox Code Playgroud)
然后告诉Spring's SecurityContextHolder存储此Authentication实例:
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(securityContext);
Run Code Online (Sandbox Code Playgroud)
现在,如果您的代码需要Authentication返回某些内容(可能是用户名)Authentication,则可以按照通常的方式对模拟实例设置一些期望值,例如
Mockito.when(authentication.getName()).thenReturn("aName");
Run Code Online (Sandbox Code Playgroud)
这与您已经在做的事情非常接近,但是您只是在嘲笑错误的类型。
更新1:针对此OP更新:
我现在可以摆脱测试类中的错误。我调试了代码,在测试类中看到securityContext具有价值。但是,当我跳到控制器建议中的代码时,以下get返回null:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
您只需要对嘲笑设置期望值Authentication,例如:
UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken("aUserName", "aPassword");
Mockito.when(authentication.getPrincipal()).thenReturn(principal);
Run Code Online (Sandbox Code Playgroud)
与上面的代码这一行...
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Run Code Online (Sandbox Code Playgroud)
...将返回UsernamePasswordAuthenticationToken。
由于您使用的是自定义类型(ApiKeyAuthentication我想?),您应该只authentication.getPrincipal()返回该类型而不是UsernamePasswordAuthenticationToken。
| 归档时间: |
|
| 查看次数: |
5359 次 |
| 最近记录: |