Search in sources :

Example 26 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class UserConsentWithUserStorageModelTest method setupEnv.

public static void setupEnv(KeycloakSession session) {
    KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession sessionSetUpEnv) -> {
        KeycloakSession currentSession = sessionSetUpEnv;
        RealmManager realmManager = new RealmManager(currentSession);
        RealmModel realm = realmManager.createRealm("original");
        UserStorageProviderModel model = new UserStorageProviderModel();
        model.setName("memory");
        model.setPriority(0);
        model.setProviderId(UserMapStorageFactory.PROVIDER_ID);
        model.setParentId(realm.getId());
        model.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));
        realm.addComponentModel(model);
        ClientModel fooClient = realm.addClient("foo-client");
        ClientModel barClient = realm.addClient("bar-client");
        ClientScopeModel fooScope = realm.addClientScope("foo");
        fooScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        ClientScopeModel barScope = realm.addClientScope("bar");
        fooScope.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        UserModel john = currentSession.users().addUser(realm, "john");
        UserModel mary = currentSession.users().addUser(realm, "mary");
        UserConsentModel johnFooGrant = new UserConsentModel(fooClient);
        johnFooGrant.addGrantedClientScope(fooScope);
        realmManager.getSession().users().addConsent(realm, john.getId(), johnFooGrant);
        UserConsentModel johnBarGrant = new UserConsentModel(barClient);
        johnBarGrant.addGrantedClientScope(barScope);
        // Update should fail as grant doesn't yet exists
        try {
            currentSession.users().updateConsent(realm, john.getId(), johnBarGrant);
            Assert.fail("Not expected to end here");
        } catch (ModelException expected) {
        }
        realmManager.getSession().users().addConsent(realm, john.getId(), johnBarGrant);
        UserConsentModel maryFooGrant = new UserConsentModel(fooClient);
        maryFooGrant.addGrantedClientScope(fooScope);
        realmManager.getSession().users().addConsent(realm, mary.getId(), maryFooGrant);
        ClientStorageProviderModel clientStorage = new ClientStorageProviderModel();
        clientStorage.setProviderId(HardcodedClientStorageProviderFactory.PROVIDER_ID);
        clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.CLIENT_ID, "hardcoded-client");
        clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.REDIRECT_URI, "http://localhost:8081/*");
        clientStorage.getConfig().putSingle(HardcodedClientStorageProviderFactory.CONSENT, "true");
        clientStorage.setParentId(realm.getId());
        clientStorageComponent = realm.addComponentModel(clientStorage);
        ClientModel hardcodedClient = currentSession.clients().getClientByClientId(realm, "hardcoded-client");
        Assert.assertNotNull(hardcodedClient);
        UserConsentModel maryHardcodedGrant = new UserConsentModel(hardcodedClient);
        realmManager.getSession().users().addConsent(realm, mary.getId(), maryHardcodedGrant);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) ModelException(org.keycloak.models.ModelException) KeycloakSession(org.keycloak.models.KeycloakSession) ClientScopeModel(org.keycloak.models.ClientScopeModel) RealmManager(org.keycloak.services.managers.RealmManager) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) ClientStorageProviderModel(org.keycloak.storage.client.ClientStorageProviderModel) UserConsentModel(org.keycloak.models.UserConsentModel)

Example 27 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class LDAPIdentityStore method addMemberToGroup.

@Override
public void addMemberToGroup(String groupDn, String memberAttrName, String value) {
    // do not check EMPTY_MEMBER_ATTRIBUTE_VALUE, we save one useless query
    // the value will be there forever for objectclasses that enforces the attribute as MUST
    BasicAttribute attr = new BasicAttribute(memberAttrName, value);
    ModificationItem item = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr);
    try {
        this.operationManager.modifyAttributesNaming(groupDn, new ModificationItem[] { item }, null);
    } catch (AttributeInUseException e) {
        logger.debugf("Group %s already contains the member %s", groupDn, value);
    } catch (NamingException e) {
        throw new ModelException("Could not modify attribute for DN [" + groupDn + "]", e);
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) ModificationItem(javax.naming.directory.ModificationItem) ModelException(org.keycloak.models.ModelException) NamingException(javax.naming.NamingException) AttributeInUseException(javax.naming.directory.AttributeInUseException)

Example 28 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class LDAPIdentityStore method getEntryIdentifier.

protected String getEntryIdentifier(final LDAPObject ldapObject) {
    try {
        // we need this to retrieve the entry's identifier from the ldap server
        String uuidAttrName = getConfig().getUuidLDAPAttributeName();
        String rdn = ldapObject.getDn().getFirstRdn().toString(false);
        String filter = "(" + EscapeStrategy.DEFAULT.escape(rdn) + ")";
        List<SearchResult> search = this.operationManager.search(ldapObject.getDn().toString(), filter, Arrays.asList(uuidAttrName), SearchControls.OBJECT_SCOPE);
        Attribute id = search.get(0).getAttributes().get(getConfig().getUuidLDAPAttributeName());
        if (id == null) {
            throw new ModelException("Could not retrieve identifier for entry [" + ldapObject.getDn().toString() + "].");
        }
        return this.operationManager.decodeEntryUUID(id.get());
    } catch (NamingException ne) {
        throw new ModelException("Could not retrieve identifier for entry [" + ldapObject.getDn().toString() + "].");
    }
}
Also used : ModelException(org.keycloak.models.ModelException) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException)

Example 29 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class LDAPIdentityStore method queryServerCapabilities.

@Override
public Set<LDAPCapabilityRepresentation> queryServerCapabilities() {
    Set<LDAPCapabilityRepresentation> result = new LinkedHashSet<>();
    try {
        List<String> attrs = new ArrayList<>();
        attrs.add("supportedControl");
        attrs.add("supportedExtension");
        attrs.add("supportedFeatures");
        List<SearchResult> searchResults = operationManager.search("", "(objectClass=*)", Collections.unmodifiableCollection(attrs), SearchControls.OBJECT_SCOPE);
        if (searchResults.size() != 1) {
            throw new ModelException("Could not query root DSE: unexpected result size");
        }
        SearchResult rootDse = searchResults.get(0);
        Attributes attributes = rootDse.getAttributes();
        for (String attr : attrs) {
            Attribute attribute = attributes.get(attr);
            if (null != attribute) {
                CapabilityType capabilityType = CapabilityType.fromRootDseAttributeName(attr);
                NamingEnumeration<?> values = attribute.getAll();
                while (values.hasMoreElements()) {
                    Object o = values.nextElement();
                    LDAPCapabilityRepresentation capability = new LDAPCapabilityRepresentation(o, capabilityType);
                    logger.info("rootDSE query: " + capability);
                    result.add(capability);
                }
            }
        }
        return result;
    } catch (NamingException e) {
        throw new ModelException("Failed to query root DSE: " + e.getMessage(), e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) CapabilityType(org.keycloak.representations.idm.LDAPCapabilityRepresentation.CapabilityType) ModelException(org.keycloak.models.ModelException) LDAPCapabilityRepresentation(org.keycloak.representations.idm.LDAPCapabilityRepresentation) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) NamingException(javax.naming.NamingException)

Example 30 with ModelException

use of org.keycloak.models.ModelException in project keycloak by keycloak.

the class LDAPIdentityStore method updateADPassword.

private void updateADPassword(String userDN, String password, LDAPOperationDecorator passwordUpdateDecorator) {
    try {
        // Replace the "unicdodePwd" attribute with a new value
        // Password must be both Unicode and a quoted string
        String newQuotedPassword = "\"" + password + "\"";
        byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
        BasicAttribute unicodePwd = new BasicAttribute("unicodePwd", newUnicodePassword);
        List<ModificationItem> modItems = new ArrayList<ModificationItem>();
        modItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, unicodePwd));
        operationManager.modifyAttributes(userDN, modItems.toArray(new ModificationItem[] {}), passwordUpdateDecorator);
    } catch (ModelException me) {
        throw me;
    } catch (Exception e) {
        throw new ModelException(e);
    }
}
Also used : BasicAttribute(javax.naming.directory.BasicAttribute) ModificationItem(javax.naming.directory.ModificationItem) ModelException(org.keycloak.models.ModelException) ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) AttributeInUseException(javax.naming.directory.AttributeInUseException) NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ModelException(org.keycloak.models.ModelException) SchemaViolationException(javax.naming.directory.SchemaViolationException)

Aggregations

ModelException (org.keycloak.models.ModelException)74 RealmModel (org.keycloak.models.RealmModel)20 NamingException (javax.naming.NamingException)13 UserModel (org.keycloak.models.UserModel)13 ClientModel (org.keycloak.models.ClientModel)11 ComponentModel (org.keycloak.component.ComponentModel)10 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)10 IOException (java.io.IOException)9 Consumes (javax.ws.rs.Consumes)9 NotFoundException (javax.ws.rs.NotFoundException)8 BasicAttribute (javax.naming.directory.BasicAttribute)7 KeycloakSession (org.keycloak.models.KeycloakSession)7 RoleModel (org.keycloak.models.RoleModel)7 ErrorResponseException (org.keycloak.services.ErrorResponseException)7 ReadOnlyException (org.keycloak.storage.ReadOnlyException)7 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 AttributeInUseException (javax.naming.directory.AttributeInUseException)5