I have an application secured by keycloak which works fine. Now I want to write Tests to check my security settings like roles.
This works fine with
@WithMockUser(roles = "customer")
annotion upon my test. In my corresponding Conroller I use the Authentication auth Object to read the keycloak userId and other stuff from the token. Is there a way to mock this??
Controller:
@PreAuthorize("hasRole('owner') || hasRole('customer') ")
@ApiOperation("Get a list of all products")
@GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Product> findAllProducts(Authentication auth)
{
SimpleKeycloakAccount account = ((SimpleKeycloakAccount) auth.getDetails());
KeycloakSecurityContext context = account.getKeycloakSecurityContext();
AccessToken token = context.getToken();
String userId = token.getSubject();
return productService.findAll();
}
TEST:
@Test
@WithMockUser(roles = "customer")
void getAllProductsWithEmptyDatabase() throws Exception {
MvcResult response = mockMvc.perform(get(URL))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().string(objectMapper.writeValueAsString(Collections.emptyList())))
.andReturn();
}
Aucun commentaire:
Enregistrer un commentaire