Example usage for javax.naming.directory DirContext bind

List of usage examples for javax.naming.directory DirContext bind

Introduction

In this page you can find the example usage for javax.naming.directory DirContext bind.

Prototype

public void bind(String name, Object obj, Attributes attrs) throws NamingException;

Source Link

Document

Binds a name to an object, along with associated attributes.

Usage

From source file:org.springframework.ldap.test.unboundid.LdapTestUtils.java

@SuppressWarnings("deprecation")
private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
    try {//from   ww  w .j  ava2  s . c om
        LdapName baseDn = (LdapName) context.getEnvironment()
                .get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);

        LdifParser parser = new LdifParser(ldifFile);
        parser.open();
        while (parser.hasMoreRecords()) {
            LdapAttributes record = parser.getRecord();

            LdapName dn = record.getName();

            if (baseDn != null) {
                dn = LdapUtils.removeFirst(dn, baseDn);
            }

            if (!rootNode.isEmpty()) {
                dn = LdapUtils.prepend(dn, rootNode);
            }
            context.bind(dn, null, record);
        }
    } catch (Exception e) {
        throw new UncategorizedLdapException("Failed to populate LDIF", e);
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public void addServicePrinciple(String serverName, String serverDescription, Object credentials)
        throws DirectoryServerManagerException {

    if (!(credentials instanceof String)) {
        throw new DirectoryServerManagerException("Invalid credentials provided");
    }//from   w  ww . ja va 2s  .com

    DirContext dirContext;
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("An error occurred while retrieving LDAP connection context.",
                e);
    }

    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    try {

        dirContext = (DirContext) dirContext.lookup(searchBase);

        BasicAttributes basicAttributes = new BasicAttributes(true);

        // Put only service name as uid. i.e. if server name is like ftp/wso2.example.com
        // then add only ftp as uid
        String serverUid = getServiceName(serverName);

        constructBasicAttributes(basicAttributes, serverUid, serverName, credentials, serverDescription,
                LDAPServerManagerConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE);

        dirContext.bind(LDAPServerManagerConstants.LDAP_UID + "=" + serverUid, null, basicAttributes);

    } catch (NamingException e) {
        String message = "Can not access the directory context or user " + "already exists in the system";
        log.error(message, e);
        throw new DirectoryServerManagerException(message, e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 *
 *///  w  w  w  . j  a  v a  2 s  .  c om
public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims,
        String profileName, boolean requirePasswordChange) throws UserStoreException {

    boolean isUserBinded = false;

    /* getting search base directory context */
    DirContext dirContext = getSearchBaseDirectoryContext();

    /* getting add user basic attributes */
    BasicAttributes basicAttributes = getAddUserBasicAttributes(userName);

    if (!isADLDSRole) {
        // creating a disabled user account in AD DS
        BasicAttribute userAccountControl = new BasicAttribute(
                LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL);
        userAccountControl.add(LDAPConstants.ACTIVE_DIRECTORY_DISABLED_NORMAL_ACCOUNT);
        basicAttributes.put(userAccountControl);
    }

    /* setting claims */
    setUserClaims(claims, basicAttributes, userName);

    Name compoundName = null;
    try {
        NameParser ldapParser = dirContext.getNameParser("");
        compoundName = ldapParser.parse("cn=" + escapeSpecialCharactersForDN(userName));

        /* bind the user. A disabled user account with no password */
        dirContext.bind(compoundName, null, basicAttributes);
        isUserBinded = true;

        /* update the user roles */
        doUpdateRoleListOfUser(userName, null, roleList);

        /* reset the password and enable the account */
        if (!isSSLConnection) {
            logger.warn("Unsecured connection is being used. Enabling user account operation will fail");
        }

        ModificationItem[] mods = new ModificationItem[2];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                        createUnicodePassword((String) credential)));
        if (isADLDSRole) {
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_MSDS_USER_ACCOUNT_DISSABLED, "FALSE"));
        } else {
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
                    LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL, userAccountControl));
        }
        dirContext.modifyAttributes(compoundName, mods);

    } catch (NamingException e) {
        String errorMessage = "Error while adding the user to the Active Directory for user : " + userName;
        if (isUserBinded) {
            try {
                dirContext.unbind(compoundName);
            } catch (NamingException e1) {
                errorMessage = "Error while accessing the Active Directory for user : " + userName;
                throw new UserStoreException(errorMessage, e);
            }
            errorMessage = "Error while enabling the user account. Please check password policy at DC for user : "
                    + userName;
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@Override
public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims,
        String profileName, boolean requirePasswordChange) throws UserStoreException {

    /* getting search base directory context */
    DirContext dirContext = getSearchBaseDirectoryContext();

    /* getting add user basic attributes */
    BasicAttributes basicAttributes = getAddUserBasicAttributes(escapeSpecialCharactersForDN(userName));

    BasicAttribute userPassword = new BasicAttribute("userPassword");
    userPassword.add(UserCoreUtil.getPasswordToStore((String) credential,
            this.realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD), kdcEnabled));
    basicAttributes.put(userPassword);/*from   ww w.  j  ava2 s  . c  o m*/

    /* setting claims */
    setUserClaims(claims, basicAttributes, userName);

    try {

        NameParser ldapParser = dirContext.getNameParser("");
        Name compoundName = ldapParser.parse(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE)
                + "=" + escapeSpecialCharactersForDN(userName));

        if (log.isDebugEnabled()) {
            log.debug("Binding user: " + compoundName);
        }
        dirContext.bind(compoundName, null, basicAttributes);
    } catch (NamingException e) {
        String errorMessage = "Cannot access the directory context or "
                + "user already exists in the system for user :" + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }

    try {
        /* update the user roles */
        doUpdateRoleListOfUser(userName, null, roleList);
        if (log.isDebugEnabled()) {
            log.debug("Roles are added for user  : " + userName + " successfully.");
        }
    } catch (UserStoreException e) {
        String errorMessage = "User is added. But error while updating role list of user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

protected void addLDAPRole(RoleContext context) throws UserStoreException {

    String roleName = context.getRoleName();
    String[] userList = context.getMembers();
    String groupEntryObjectClass = ((LDAPRoleContext) context).getGroupEntryObjectClass();
    String groupNameAttribute = ((LDAPRoleContext) context).getRoleNameProperty();
    String searchBase = ((LDAPRoleContext) context).getSearchBase();

    if ((userList == null || userList.length == 0) && !emptyRolesAllowed) {
        String errorMessage = "Can not create empty role. There should be at least " + "one user for the role.";
        throw new UserStoreException(errorMessage);
    } else if (userList == null && emptyRolesAllowed
            || userList != null && userList.length > 0 && !emptyRolesAllowed || emptyRolesAllowed) {

        // if (userList.length > 0) {
        DirContext mainDirContext = this.connectionSource.getContext();
        DirContext groupContext = null;
        NamingEnumeration<SearchResult> results = null;

        try {/*from w  w  w. j av a 2s.co  m*/
            // create the attribute set for group entry
            Attributes groupAttributes = new BasicAttributes(true);

            // create group entry's object class attribute
            Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
            objectClassAttribute.add(groupEntryObjectClass);
            groupAttributes.put(objectClassAttribute);

            // create cn attribute
            Attribute cnAttribute = new BasicAttribute(groupNameAttribute);
            cnAttribute.add(roleName);
            groupAttributes.put(cnAttribute);
            // following check is for if emptyRolesAllowed made this
            // code executed.
            if (userList != null && userList.length > 0) {

                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                Attribute memberAttribute = new BasicAttribute(memberAttributeName);
                for (String userName : userList) {

                    if (userName == null || userName.trim().length() == 0) {
                        continue;
                    }
                    // search the user in user search base
                    String searchFilter = realmConfig
                            .getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
                    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
                    results = searchInUserBase(searchFilter, new String[] {}, SearchControls.SUBTREE_SCOPE,
                            mainDirContext);
                    // we assume only one user with the given user
                    // name under user search base.
                    SearchResult userResult = null;
                    if (results.hasMore()) {
                        userResult = results.next();
                    } else {
                        String errorMsg = "There is no user with the user name: " + userName
                                + " to be added to this role.";
                        logger.error(errorMsg);
                        throw new UserStoreException(errorMsg);
                    }
                    // get his DN
                    String userEntryDN = userResult.getNameInNamespace();
                    // put it as member-attribute value
                    memberAttribute.add(userEntryDN);
                }
                groupAttributes.put(memberAttribute);
            }

            groupContext = (DirContext) mainDirContext.lookup(searchBase);
            NameParser ldapParser = groupContext.getNameParser("");
            /*
             * Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" +
             * roleName);
             */
            Name compoundGroupName = ldapParser.parse("cn=" + roleName);
            groupContext.bind(compoundGroupName, null, groupAttributes);

        } catch (NamingException e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } catch (Exception e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(results);
            JNDIUtil.closeContext(groupContext);
            JNDIUtil.closeContext(mainDirContext);
        }

    }

}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

@Deprecated
protected String createAdminEntry(String dnOfUserContext, Tenant tenant, DirContext initialDirContext)
        throws UserStoreException {
    String userDN = null;//from w w w  .j av a2s .  com
    DirContext organizationalUsersContext = null;
    try {
        //get connection to tenant's user context
        organizationalUsersContext = (DirContext) initialDirContext.lookup(dnOfUserContext);
        Attributes userAttributes = new BasicAttributes(true);

        //create person object class attribute
        Attribute objClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
        objClass.add(realmConfig.getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS));
        if (UserCoreUtil.isKdcEnabled(realmConfig)) {
            // Add Kerberos specific object classes
            objClass.add("krb5principal");
            objClass.add("krb5kdcentry");
            objClass.add("subschema");

            String principal = tenant.getAdminName() + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR
                    + tenant.getDomain() + UserCoreConstants.TENANT_DOMAIN_COMBINER + getRealmName();
            Attribute kerberosPrincipalName = new BasicAttribute("krb5PrincipalName");
            kerberosPrincipalName.add(principal);

            Attribute keyVersionNumber = new BasicAttribute("krb5KeyVersionNumber");
            keyVersionNumber.add("0");

            userAttributes.put(kerberosPrincipalName);
            userAttributes.put(keyVersionNumber);
        }
        userAttributes.put(objClass);

        //create user password attribute
        Attribute password = new BasicAttribute(USER_PASSWORD_ATTRIBUTE_NAME);
        String passwordHashMethod = realmConfig.getUserStoreProperty(LDAPConstants.PASSWORD_HASH_METHOD);
        String passwordToStore = UserCoreUtil.getPasswordToStore(tenant.getAdminPassword(), passwordHashMethod,
                isKDCEnabled());
        password.add(passwordToStore);
        userAttributes.put(password);

        //create mail attribute
        Attribute adminEmail = new BasicAttribute(EMAIL_ATTRIBUTE_NAME);
        adminEmail.add(tenant.getEmail());
        userAttributes.put(adminEmail);

        //create compulsory attribute: sn-last name
        Attribute lastName = new BasicAttribute(SN_ATTRIBUTE_NAME);
        lastName.add(tenant.getAdminLastName());
        userAttributes.put(lastName);

        //read user name attribute in user-mgt.xml
        String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);

        //if user name attribute is not cn, add it to attribute list
        if (!(CN_ATTRIBUTE_NAME.equals(userNameAttribute))) {
            Attribute firstName = new BasicAttribute(CN_ATTRIBUTE_NAME);
            firstName.add(tenant.getAdminFirstName());
            userAttributes.put(firstName);
        }
        String userRDN = userNameAttribute + "=" + tenant.getAdminName();
        organizationalUsersContext.bind(userRDN, null, userAttributes);
        userDN = userRDN + "," + dnOfUserContext;
        //return (userRDN + dnOfUserContext);
    } catch (NamingException e) {
        String errorMsg = "Error occurred while creating Admin entry";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        closeContext(organizationalUsersContext);
    }

    return userDN;
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

@Deprecated
protected void createAdminGroup(String dnOfGroupContext, String adminUserDN, DirContext initialDirContext)
        throws UserStoreException {
    //create set of attributes required to create admin group
    Attributes adminGroupAttributes = new BasicAttributes(true);
    //admin entry object class
    Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
    objectClassAttribute.add(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_ENTRY_OBJECT_CLASS));
    adminGroupAttributes.put(objectClassAttribute);

    //group name attribute
    String groupNameAttributeName = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    Attribute groupNameAttribute = new BasicAttribute(groupNameAttributeName);
    String adminRoleName = realmConfig.getAdminRoleName();
    groupNameAttribute.add(UserCoreUtil.removeDomainFromName(adminRoleName));
    adminGroupAttributes.put(groupNameAttribute);

    //membership attribute
    Attribute membershipAttribute = new BasicAttribute(
            realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE));
    membershipAttribute.add(adminUserDN);
    adminGroupAttributes.put(membershipAttribute);

    DirContext groupContext = null;
    try {//from  w w  w .  j  av a  2  s. c om
        groupContext = (DirContext) initialDirContext.lookup(dnOfGroupContext);
        String rdnOfAdminGroup = groupNameAttributeName + "="
                + UserCoreUtil.removeDomainFromName(adminRoleName);
        groupContext.bind(rdnOfAdminGroup, null, adminGroupAttributes);

    } catch (NamingException e) {
        String errorMessage = "Error occurred while creating the admin group.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        closeContext(groupContext);
    }
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

public void addSharedGroupForTenant(Tenant tenant, DirContext mainDirContext) throws UserStoreException {

    if (!isSharedGroupEnabled()) {
        return;//  www.  j  a va2  s. c  o m
    }
    Attributes groupAttributes = new BasicAttributes(true);

    String domainName = tenant.getDomain();
    // create ou attribute
    String groupNameAttributeName = realmConfig
            .getUserStoreProperty(LDAPConstants.SHARED_TENANT_NAME_ATTRIBUTE);

    // create group entry's object class attribute
    Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
    objectClassAttribute.add(realmConfig.getUserStoreProperty(LDAPConstants.SHARED_TENANT_OBJECT_CLASS));
    groupAttributes.put(objectClassAttribute);

    DirContext groupContext = null;

    String searchBase = realmConfig.getUserStoreProperties().get(LDAPConstants.SHARED_GROUP_SEARCH_BASE);

    try {
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        NameParser ldapParser = groupContext.getNameParser("");
        Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" + domainName);
        groupContext.bind(compoundGroupName, null, groupAttributes);

    } catch (Exception e) {
        String errorMsg = "Shared tenant: " + domainName + "could not be added.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        JNDIUtil.closeContext(groupContext);
    }

}