Skip to content
Snippets Groups Projects
Commit aecf61a3 authored by nsmoliak's avatar nsmoliak
Browse files

move embedded keycloak test

parent 6cbb98af
No related tags found
No related merge requests found
package eu.gaiax.difs.fc.server.controller;
import static eu.gaiax.difs.fc.server.util.CommonConstants.CATALOGUE_ADMIN_ROLE;
import static eu.gaiax.difs.fc.server.util.CommonConstants.SD_ADMIN_ROLE;
import static eu.gaiax.difs.fc.server.util.TestCommonConstants.CATALOGUE_ADMIN_ROLE_WITH_PREFIX;
import static eu.gaiax.difs.fc.server.util.TestCommonConstants.CATALOGUE_PARTICIPANT_ADMIN_ROLE_ID;
import static eu.gaiax.difs.fc.server.util.TestCommonConstants.DEFAULT_GAIAX_REALM_ROLE;
import static eu.gaiax.difs.fc.server.util.TestCommonConstants.DEFAULT_PARTICIPANT_ID;
import static eu.gaiax.difs.fc.server.util.TestCommonConstants.SD_ADMIN_ROLE_ID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.keycloak.OAuth2Constants.CLIENT_ID;
import static org.keycloak.OAuth2Constants.CLIENT_SECRET;
import static org.keycloak.OAuth2Constants.GRANT_TYPE;
import static org.keycloak.OAuth2Constants.PASSWORD;
import static org.keycloak.OAuth2Constants.USERNAME;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
......@@ -16,15 +22,36 @@ import eu.gaiax.difs.fc.api.generated.model.Error;
import eu.gaiax.difs.fc.core.dao.UserDao;
import eu.gaiax.difs.fc.server.controller.common.EmbeddedKeycloakTest;
import eu.gaiax.difs.fc.testsupport.config.EmbeddedKeycloakApplication;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.BasicAuthFilter;
import org.keycloak.admin.client.token.TokenService;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.services.managers.RealmManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.event.annotation.BeforeTestClass;
import org.springframework.test.web.servlet.MockMvc;
......@@ -45,6 +72,14 @@ import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
@AutoConfigureEmbeddedDatabase(provider = AutoConfigureEmbeddedDatabase.DatabaseProvider.ZONKY)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {"server.port=9091"})
public class UsersControllerTest extends EmbeddedKeycloakTest {
@Value("${keycloak.realm}")
private String realmName;
@Value("${keycloak.resource}")
private String clientId;
@Value("${keycloak.credentials.secret}")
private String clientSecret;
@Value("${keycloak.auth-server-url}")
private String serverUrl;
@Autowired
private WebApplicationContext context;
@Autowired
......@@ -183,7 +218,24 @@ public class UsersControllerTest extends EmbeddedKeycloakTest {
UserProfile profile = objectMapper.readValue(response, UserProfile.class);
assertThatResponseUserHasValidData(user, profile);
}
@Test
public void deleteUserAndKeycloakAccessShouldReturnUnauthorizedError() throws Exception {
UserModel user = createUser("newuser", "newuser", CATALOGUE_ADMIN_ROLE);
AccessTokenResponse accessTokenResponse = grantToken("newuser", "newuser");
String response = mockMvc
.perform(MockMvcRequestBuilders.delete("/users/{userId}", user.getId())
.with(authentication(new BearerTokenAuthenticationToken(accessTokenResponse.getToken())))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
UserProfile profile = objectMapper.readValue(response, UserProfile.class);
assertThrows(NotFoundException.class, () -> userDao.delete(profile.getId()));
assertThrows(NotAuthorizedException.class, () -> grantToken("newuser", "newuser"));
}
@Test
@WithMockUser(authorities = {CATALOGUE_ADMIN_ROLE_WITH_PREFIX})
public void updateUserShouldReturnSuccessResponse() throws Exception {
......@@ -282,4 +334,43 @@ public class UsersControllerTest extends EmbeddedKeycloakTest {
assertTrue(actual.getRoleIds().containsAll(excepted.getRoleIds()));
assertEquals(excepted.getParticipantId(), actual.getParticipantId());
}
public AccessTokenResponse grantToken(String username, String password) {
MultivaluedMap<String, String> body = new MultivaluedHashMap<>();
body.add(GRANT_TYPE, PASSWORD);
body.add(USERNAME, username);
body.add(PASSWORD, password);
body.add(CLIENT_ID, clientId);
body.add(CLIENT_SECRET, clientSecret);
WebTarget target = new ResteasyClientBuilder().connectionPoolSize(5).build().target(serverUrl);
target.register(new BasicAuthFilter(clientId, clientSecret));
return Keycloak.getClientProvider().targetProxy(target, TokenService.class).grantToken(realmName, body);
}
private UserModel createUser(String username, String password, String role) {
KeycloakSession session = EmbeddedKeycloakApplication.getSessionFactory().create();
try {
session.getTransactionManager().begin();
RealmManager manager = new RealmManager(session);
RealmModel realm = manager.getRealm(realmName);
RoleModel roleModel = realm.getRole(role);
UserModel userModel = session.users().getUserByUsername(realm, username);
if (userModel == null) {
userModel = session.users().addUser(realm, UUID.randomUUID().toString(), username, true, true);
userModel.grantRole(roleModel);
userModel.setEmail(username + "@test.com");
userModel.setEnabled(true);
session.userCredentialManager()
.updateCredential(realm, userModel, UserCredentialModel.password(password));
}
session.getTransactionManager().commit();
session.close();
return userModel;
} catch (Exception ex) {
session.getTransactionManager().rollback();
session.close();
throw ex;
}
}
}
......@@ -17,6 +17,7 @@ import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.managers.RealmManager;
import org.springframework.beans.factory.annotation.Value;
......@@ -56,7 +57,10 @@ public class EmbeddedKeycloakTest {
catalogAdmin =
session.users().addUser(realm, UUID.randomUUID().toString(), CATALOGUE_ADMIN_USERNAME, true, true);
catalogAdmin.grantRole(catalogAdminRole);
catalogAdmin.setEmail(CATALOGUE_ADMIN_USERNAME + "@gmail.com");
catalogAdmin.setEnabled(true);
catalogAdmin.joinGroup(group);
session.userCredentialManager().updateCredential(realm, catalogAdmin, UserCredentialModel.password("catalog_admin"));
}
session.getTransactionManager().commit();
} catch (Exception ex) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment