I have a Spring Boot based app that us using ISAM Authentication from an external provider.
I have a rest/json endpoint /actuator/health
that returns different data depending on if the user is authenticated or not.
How can I mock authentication during unit testing to ensure my configuration is correct?
In setup()
, I've tried setting a token manually, and overriding AuthorizationService to return true.
@Before
public void setUp() throws Exception
{
mockMvc = webAppContextSetup(wac).apply(springSecurity()).build();
List roles = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken("dave", "secret",
roles);
if (!auth.isAuthenticated()) { fail("NOT AUTHENTICATED!"); }
SecurityContextHolder.getContext().setAuthentication(auth);
//fake logged in
when(authorizationService.isCurrentUserAuthorized(anyString(),
anyString(),
ArgumentMatchers.any(ResourceType.class),
ArgumentMatchers.any(ActionType.class)))
.thenReturn(true);
}
However, when I run
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!auth.isAuthenticated()) { fail("NOT AUTHENTICATED!"); }
UsernamePasswordAuthenticationToken authToken =
(UsernamePasswordAuthenticationToken)auth;
mockMvc.perform(get("/health_secure")
.principal(auth)
.header("Authorization", "Bearer " + token))
.andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("/actuator/health"));
I get:
"error":"invalid_token","error_description":"Cannot convert access token to JSON"