use of org.keycloak.models.ModelException in project keycloak by keycloak.
the class UserStorageProvidersTestUtils method getStorageProvider.
public static UserStorageProvider getStorageProvider(KeycloakSession session, RealmModel realm, String componentId) {
ComponentModel model = realm.getComponent(componentId);
if (model == null)
return null;
UserStorageProviderModel storageModel = new UserStorageProviderModel(model);
UserStorageProviderFactory factory = (UserStorageProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, model.getProviderId());
if (factory == null) {
throw new ModelException("Could not find UserStorageProviderFactory for: " + model.getProviderId());
}
return getStorageProviderInstance(session, storageModel, factory);
}
use of org.keycloak.models.ModelException in project keycloak by keycloak.
the class ClientRoleMappingsResource method addClientRoleMapping.
/**
* Add client-level roles to the user role mapping
*
* @param roles
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void addClientRoleMapping(List<RoleRepresentation> roles) {
managePermission.require();
try {
for (RoleRepresentation role : roles) {
RoleModel roleModel = client.getRole(role.getName());
if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found");
}
auth.roles().requireMapRole(roleModel);
user.grantRole(roleModel);
}
} catch (ModelException | ReadOnlyException me) {
logger.warn(me.getMessage(), me);
throw new ErrorResponseException("invalid_request", "Could not add user role mappings!", Response.Status.BAD_REQUEST);
}
adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(roles).success();
}
use of org.keycloak.models.ModelException in project keycloak by keycloak.
the class ClientRoleMappingsResource method deleteClientRoleMapping.
/**
* Delete client-level roles from user role mapping
*
* @param roles
*/
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
public void deleteClientRoleMapping(List<RoleRepresentation> roles) {
managePermission.require();
if (roles == null) {
roles = user.getClientRoleMappingsStream(client).peek(roleModel -> {
auth.roles().requireMapRole(roleModel);
user.deleteRoleMapping(roleModel);
}).map(ModelToRepresentation::toBriefRepresentation).collect(Collectors.toList());
} else {
for (RoleRepresentation role : roles) {
RoleModel roleModel = client.getRole(role.getName());
if (roleModel == null || !roleModel.getId().equals(role.getId())) {
throw new NotFoundException("Role not found");
}
auth.roles().requireMapRole(roleModel);
try {
user.deleteRoleMapping(roleModel);
} catch (ModelException | ReadOnlyException me) {
logger.warn(me.getMessage(), me);
throw new ErrorResponseException("invalid_request", "Could not remove user role mappings!", Response.Status.BAD_REQUEST);
}
}
}
adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).representation(roles).success();
}
use of org.keycloak.models.ModelException in project keycloak by keycloak.
the class RealmAdminResource method updateRealm.
/**
* Update the top-level information of the realm
*
* Any user, roles or client information in the representation
* will be ignored. This will only update top-level attributes of the realm.
*
* @param rep
* @return
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateRealm(final RealmRepresentation rep) {
auth.realm().requireManageRealm();
logger.debug("updating realm: " + realm.getName());
if (Config.getAdminRealm().equals(realm.getName()) && (rep.getRealm() != null && !rep.getRealm().equals(Config.getAdminRealm()))) {
return ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST);
}
ReservedCharValidator.validate(rep.getRealm());
ReservedCharValidator.validateLocales(rep.getSupportedLocales());
try {
if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getPrivateKey() != null && rep.getPublicKey() != null)) {
try {
KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey());
} catch (VerificationException e) {
return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
}
}
if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getCertificate() != null)) {
try {
X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate());
if (cert == null) {
return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
}
} catch (Exception e) {
return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
}
}
boolean wasDuplicateEmailsAllowed = realm.isDuplicateEmailsAllowed();
RepresentationToModel.updateRealm(rep, realm, session);
// Refresh periodic sync tasks for configured federationProviders
UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
realm.getUserStorageProvidersStream().forEachOrdered(fedProvider -> usersSyncManager.notifyToRefreshPeriodicSync(session, realm, fedProvider, false));
// This populates the map in DefaultKeycloakContext to be used when treating the event
session.getContext().getUri();
adminEvent.operation(OperationType.UPDATE).representation(StripSecretsUtils.strip(rep)).success();
if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) {
UserCache cache = session.getProvider(UserCache.class);
if (cache != null)
cache.clear();
}
return Response.noContent().build();
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("Realm with same name exists");
} catch (ModelException e) {
return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR);
}
}
use of org.keycloak.models.ModelException in project keycloak by keycloak.
the class LDAPGroupMapperTest method test02_readOnlyGroupMappings.
protected void test02_readOnlyGroupMappings(boolean importEnabled) {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "groupsMapper");
LDAPTestUtils.updateGroupMapperConfigOptions(mapperModel, GroupMapperConfig.MODE, LDAPGroupMapperMode.READ_ONLY.toString());
appRealm.updateComponent(mapperModel);
GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
// Add some group mappings directly into LDAP
GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), appRealm);
LDAPObject maryLdap = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "marykeycloak");
groupMapper.addGroupMappingInLDAP(appRealm, group1, maryLdap);
groupMapper.addGroupMappingInLDAP(appRealm, group11, maryLdap);
});
if (importEnabled) {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
// Add some group mapping to model
mary.joinGroup(group12);
// Assert that mary has both LDAP and DB mapped groups
Set<GroupModel> maryGroups = mary.getGroupsStream().collect(Collectors.toSet());
Assert.assertEquals(5, maryGroups.size());
Assert.assertTrue(maryGroups.contains(group1));
Assert.assertTrue(maryGroups.contains(group11));
Assert.assertTrue(maryGroups.contains(group12));
long groupCount = mary.getGroupsCount();
Assert.assertEquals(5, groupCount);
Assert.assertEquals(5, mary.getGroupsStream("gr", 0, 10).count());
Assert.assertEquals(4, mary.getGroupsStream("gr", 1, 10).count());
Assert.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count());
Assert.assertEquals(2, mary.getGroupsStream("12", 0, 10).count());
});
} else {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
// as it is not allowed to update group mappings in LDAP nor in the DB
try {
mary.joinGroup(group12);
Assert.fail("Not expected to successfully add group12 in no-import mode and READ_ONLY mode of the group mapper");
} catch (ModelException me) {
// Ignore
}
});
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
// Assert that mary has both LDAP and DB mapped groups
Set<GroupModel> maryGroups = mary.getGroupsStream().collect(Collectors.toSet());
Assert.assertEquals(4, maryGroups.size());
Assert.assertTrue(maryGroups.contains(group1));
Assert.assertTrue(maryGroups.contains(group11));
Assert.assertFalse(maryGroups.contains(group12));
long groupCount = mary.getGroupsCount();
Assert.assertEquals(4, groupCount);
Assert.assertEquals(4, mary.getGroupsStream("gr", 0, 10).count());
Assert.assertEquals(3, mary.getGroupsStream("gr", 1, 10).count());
Assert.assertEquals(1, mary.getGroupsStream("gr", 0, 1).count());
Assert.assertEquals(1, mary.getGroupsStream("12", 0, 10).count());
});
}
// Assert that access through DB will have just DB mapped groups
if (importEnabled) {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
UserModel maryDB = session.userLocalStorage().getUserByUsername(appRealm, "marykeycloak");
Set<GroupModel> maryDBGroups = maryDB.getGroupsStream().collect(Collectors.toSet());
Assert.assertFalse(maryDBGroups.contains(group1));
Assert.assertFalse(maryDBGroups.contains(group11));
Assert.assertTrue(maryDBGroups.contains(group12));
Assert.assertEquals(3, maryDB.getGroupsStream("Gr", 0, 10).count());
Assert.assertEquals(2, maryDB.getGroupsStream("Gr", 1, 10).count());
Assert.assertEquals(1, maryDB.getGroupsStream("Gr", 0, 1).count());
Assert.assertEquals(2, maryDB.getGroupsStream("12", 0, 10).count());
long dbGroupCount = maryDB.getGroupsCount();
Assert.assertEquals(3, dbGroupCount);
// Test the group mapping available for group12
List<UserModel> group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10).collect(Collectors.toList());
Assert.assertEquals(1, group12Members.size());
Assert.assertEquals("marykeycloak", group12Members.get(0).getUsername());
UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
mary.leaveGroup(group12);
});
} else {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
// Test the group mapping NOT available for group12
Stream<UserModel> group12Members = session.users().getGroupMembersStream(appRealm, group12, 0, 10);
Assert.assertEquals(0, group12Members.count());
});
}
// Check through userProvider
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session);
RealmModel appRealm = ctx.getRealm();
GroupModel group1 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1");
GroupModel group11 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group11");
GroupModel group12 = KeycloakModelUtils.findGroupByPath(appRealm, "/group1/group12");
UserModel john = session.users().getUserByUsername(appRealm, "johnkeycloak");
UserModel mary = session.users().getUserByUsername(appRealm, "marykeycloak");
ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "groupsMapper");
GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ctx.getLdapProvider(), appRealm);
LDAPObject maryLdap = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "marykeycloak");
List<UserModel> group1Members = session.users().getGroupMembersStream(appRealm, group1, 0, 10).collect(Collectors.toList());
List<UserModel> group11Members = session.users().getGroupMembersStream(appRealm, group11, 0, 10).collect(Collectors.toList());
Assert.assertEquals(1, group1Members.size());
Assert.assertEquals("marykeycloak", group1Members.get(0).getUsername());
Assert.assertEquals(1, group11Members.size());
Assert.assertEquals("marykeycloak", group11Members.get(0).getUsername());
try {
mary.leaveGroup(group1);
Assert.fail("It wasn't expected to successfully delete LDAP group mappings in READ_ONLY mode");
} catch (ModelException expected) {
}
// Delete group mappings directly in LDAP
LDAPObject ldapGroup = groupMapper.loadLDAPGroupByName("group1");
groupMapper.deleteGroupMappingInLDAP(maryLdap, ldapGroup);
ldapGroup = groupMapper.loadLDAPGroupByName("group11");
groupMapper.deleteGroupMappingInLDAP(maryLdap, ldapGroup);
});
}
Aggregations