use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class ClientResource method updateClientFromRep.
private void updateClientFromRep(ClientRepresentation rep, ClientModel client, KeycloakSession session) throws ModelDuplicateException {
UserModel serviceAccount = this.session.users().getServiceAccount(client);
if (TRUE.equals(rep.isServiceAccountsEnabled())) {
if (serviceAccount == null) {
new ClientManager(new RealmManager(session)).enableServiceAccount(client);
}
} else {
if (serviceAccount != null) {
new UserManager(session).removeUser(realm, serviceAccount);
}
}
if (rep.getClientId() != null && !rep.getClientId().equals(client.getClientId())) {
new ClientManager(new RealmManager(session)).clientIdChanged(client, rep);
}
if (rep.isFullScopeAllowed() != null && rep.isFullScopeAllowed() != client.isFullScopeAllowed()) {
auth.clients().requireManage(client);
}
if ((rep.isBearerOnly() != null && rep.isBearerOnly()) || (rep.isPublicClient() != null && rep.isPublicClient())) {
rep.setAuthorizationServicesEnabled(false);
}
RepresentationToModel.updateClient(rep, client);
RepresentationToModel.updateClientProtocolMappers(rep, client);
updateAuthorizationSettings(rep);
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class ClientsResource method createClient.
/**
* Create a new client
*
* Client's client_id must be unique!
*
* @param rep
* @return
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createClient(final ClientRepresentation rep) {
auth.clients().requireManage();
try {
session.clientPolicy().triggerOnEvent(new AdminClientRegisterContext(rep, auth.adminAuth()));
ClientModel clientModel = ClientManager.createClient(session, realm, rep);
if (TRUE.equals(rep.isServiceAccountsEnabled())) {
UserModel serviceAccount = session.users().getServiceAccount(clientModel);
if (serviceAccount == null) {
new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
}
}
adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();
if (Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION) && TRUE.equals(rep.getAuthorizationServicesEnabled())) {
AuthorizationService authorizationService = getAuthorizationService(clientModel);
authorizationService.enable(true);
ResourceServerRepresentation authorizationSettings = rep.getAuthorizationSettings();
if (authorizationSettings != null) {
authorizationService.resourceServer().importSettings(authorizationSettings);
}
}
ValidationUtil.validateClient(session, clientModel, true, r -> {
session.getTransactionManager().setRollbackOnly();
throw new ErrorResponseException(Errors.INVALID_INPUT, r.getAllLocalizedErrorsAsString(AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale())), Response.Status.BAD_REQUEST);
});
session.clientPolicy().triggerOnEvent(new AdminClientRegisteredContext(clientModel, auth.adminAuth()));
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
} catch (ClientPolicyException cpe) {
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class UserSessionPersisterProviderTest method testOnClientRemoved.
@Test
public void testOnClientRemoved() {
int started = Time.currentTime();
AtomicReference<String> userSessionID = new AtomicReference<>();
inComittedTransaction(session -> {
RealmModel fooRealm = session.realms().createRealm("foo", "foo");
fooRealm.setDefaultRole(session.roles().addRealmRole(fooRealm, Constants.DEFAULT_ROLES_ROLE_PREFIX));
fooRealm.addClient("foo-app");
fooRealm.addClient("bar-app");
session.users().addUser(fooRealm, "user3");
UserSessionModel userSession = session.sessions().createUserSession(fooRealm, session.users().getUserByUsername(fooRealm, "user3"), "user3", "127.0.0.1", "form", true, null, null);
userSessionID.set(userSession.getId());
createClientSession(session, realmId, fooRealm.getClientByClientId("foo-app"), userSession, "http://redirect", "state");
createClientSession(session, realmId, fooRealm.getClientByClientId("bar-app"), userSession, "http://redirect", "state");
});
inComittedTransaction(session -> {
RealmModel fooRealm = session.realms().getRealm("foo");
// Persist offline session
UserSessionModel userSession = session.sessions().getUserSession(fooRealm, userSessionID.get());
persistUserSession(session, userSession, true);
});
inComittedTransaction(session -> {
RealmManager realmMgr = new RealmManager(session);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
// Assert session was persisted with both clientSessions
UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "foo-app", "bar-app");
// Remove foo-app client
ClientModel client = fooRealm.getClientByClientId("foo-app");
clientMgr.removeClient(fooRealm, client);
});
inComittedTransaction(session -> {
RealmManager realmMgr = new RealmManager(session);
ClientManager clientMgr = new ClientManager(realmMgr);
RealmModel fooRealm = realmMgr.getRealm("foo");
// Assert just one bar-app clientSession persisted now
UserSessionModel persistedSession = loadPersistedSessionsPaginated(session, true, 10, 1, 1).get(0);
assertSession(persistedSession, session.users().getUserByUsername(fooRealm, "user3"), "127.0.0.1", started, started, "bar-app");
// Remove bar-app client
ClientModel client = fooRealm.getClientByClientId("bar-app");
clientMgr.removeClient(fooRealm, client);
});
inComittedTransaction(session -> {
// Assert loading still works - last userSession is still there, but no clientSession on it
loadPersistedSessionsPaginated(session, true, 10, 1, 1);
// Cleanup
RealmManager realmMgr = new RealmManager(session);
realmMgr.removeRealm(realmMgr.getRealm("foo"));
});
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class ClientResource method getServiceAccountUser.
/**
* Get a user dedicated to the service account
*
* @return
*/
@Path("service-account-user")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public UserRepresentation getServiceAccountUser() {
auth.clients().requireView(client);
UserModel user = session.users().getServiceAccount(client);
if (user == null) {
if (client.isServiceAccountsEnabled()) {
new ClientManager(new RealmManager(session)).enableServiceAccount(client);
user = session.users().getServiceAccount(client);
} else {
throw new BadRequestException("Service account not enabled for the client '" + client.getClientId() + "'");
}
}
return ModelToRepresentation.toRepresentation(session, realm, user);
}
use of org.keycloak.services.managers.ClientManager in project keycloak by keycloak.
the class UserModelTest method testServiceAccountLink.
@Test
@ModelTest
public void testServiceAccountLink(KeycloakSession session) throws Exception {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesServiceLink1) -> {
KeycloakSession currentSession = sesServiceLink1;
RealmModel realm = currentSession.realms().getRealmByName("original");
ClientModel client = realm.addClient("foo");
UserModel user1 = currentSession.users().addUser(realm, "user1");
user1.setFirstName("John");
user1.setLastName("Doe");
UserModel user2 = currentSession.users().addUser(realm, "user2");
user2.setFirstName("John");
user2.setLastName("Doe");
// Search
Assert.assertThat(currentSession.users().getServiceAccount(client), nullValue());
List<UserModel> users = currentSession.users().searchForUserStream(realm, "John Doe").collect(Collectors.toList());
Assert.assertThat(users, hasSize(2));
Assert.assertThat(users, containsInAnyOrder(user1, user2));
// Link service account
user1.setServiceAccountClientLink(client.getId());
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesServiceLink2) -> {
KeycloakSession currentSession = sesServiceLink2;
RealmModel realm = currentSession.realms().getRealmByName("original");
UserModel user1 = currentSession.users().getUserByUsername(realm, "user1");
UserModel user2 = currentSession.users().getUserByUsername(realm, "user2");
// Search and assert service account user not found
ClientModel client = realm.getClientByClientId("foo");
UserModel searched = currentSession.users().getServiceAccount(client);
Assert.assertThat(searched, equalTo(user1));
List<UserModel> users = currentSession.users().searchForUserStream(realm, "John Doe").collect(Collectors.toList());
Assert.assertThat(users, hasSize(1));
Assert.assertThat(users, contains(user2));
users = currentSession.users().getUsersStream(realm, false).collect(Collectors.toList());
Assert.assertThat(users, hasSize(1));
Assert.assertThat(users, contains(user2));
users = currentSession.users().getUsersStream(realm, true).collect(Collectors.toList());
Assert.assertThat(users, hasSize(2));
Assert.assertThat(users, containsInAnyOrder(user1, user2));
Assert.assertThat(currentSession.users().getUsersCount(realm, true), equalTo(2));
Assert.assertThat(currentSession.users().getUsersCount(realm, false), equalTo(1));
// Remove client
RealmManager realmMgr = new RealmManager(currentSession);
ClientManager clientMgr = new ClientManager(realmMgr);
clientMgr.removeClient(realm, client);
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sesServiceLink3) -> {
KeycloakSession currentSession = sesServiceLink3;
RealmModel realm = currentSession.realms().getRealmByName("original");
// Assert service account removed as well
Assert.assertThat(currentSession.users().getUserByUsername(realm, "user1"), nullValue());
});
}
Aggregations