Example usage for org.apache.shiro.realm.ldap LdapUtils closeContext

List of usage examples for org.apache.shiro.realm.ldap LdapUtils closeContext

Introduction

In this page you can find the example usage for org.apache.shiro.realm.ldap LdapUtils closeContext.

Prototype

public static void closeContext(LdapContext ctx) 

Source Link

Document

Closes an LDAP context, logging any errors, but not throwing an exception if there is a failure.

Usage

From source file:com.axelor.auth.AuthLdap.java

License:Open Source License

private boolean doLogin(final String user, final String password) throws NamingException {
    final NamingEnumeration<?> all = search(ldapUsersDn, ldapUserFilter, user);
    if (!all.hasMore()) {
        throw new NamingException("LDAP user does not exist: " + user);
    }/* w ww  .  j  a  v a 2 s  .  c o m*/
    while (all.hasMore()) {
        final SearchResult result = (SearchResult) all.next();
        final String dn = result.getNameInNamespace();
        LdapContext context = null;
        try {
            context = factory.getLdapContext((Object) dn, password);
        } finally {
            LdapUtils.closeContext(context);
        }
        findOrCreateUser(user, result);
        return true;
    }
    return false;
}

From source file:com.axelor.auth.AuthLdap.java

License:Open Source License

private NamingEnumeration<?> search(String where, String filter, String user) throws NamingException {

    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filterString = filter.replaceAll("\\{0\\}", user);

    LdapContext context = factory.getSystemLdapContext();
    try {//w w  w .j  a  v  a  2s  . c  o m
        return context.search(where, filterString, controls);
    } finally {
        LdapUtils.closeContext(context);
    }
}

From source file:com.axelor.auth.AuthLdap.java

License:Open Source License

private void uploadGroup(Group group) throws NamingException {

    Attributes attrs = new BasicAttributes();

    Attribute objClass = new BasicAttribute("objectClass");
    objClass.add("top");
    objClass.add(ldapGroupObjectClass);/*from  w w w . jav a 2s  .  c om*/

    Attribute cn = new BasicAttribute("cn");
    cn.add(group.getCode());

    Attribute uniqueMember = new BasicAttribute("uniqueMember");
    uniqueMember.add("uid=admin");

    attrs.put(objClass);
    attrs.put(cn);
    attrs.put(uniqueMember);

    LdapContext context = factory.getSystemLdapContext();
    try {
        context.createSubcontext("cn=" + group.getCode() + "," + ldapGroupsDn, attrs);
    } finally {
        LdapUtils.closeContext(context);
    }
}

From source file:net.minder.knox.gateway.EyKnoxLdapRealm.java

License:Apache License

protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
    String userDn;/*w w w. j  a  va 2 s .co  m*/
    Matcher matchedPrincipal = matchPrincipal(principal);
    String userSearchAttribute = getUserSearchAttributeName();

    // If not searching use the userDnTemplate and return.
    if ((userSearchFilter == null || userSearchFilter.isEmpty())
            && (userSearchAttribute == null || userSearchAttribute.isEmpty())) {
        userDn = expandTemplate(userDnTemplate, matchedPrincipal);
        LOG.debug("Computed user DN: " + userDn);
        return userDn;
    }

    // Create the searchBase and searchFilter from config.
    String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
    String searchFilter;
    if (userSearchFilter == null) {
        searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(),
                userSearchAttribute, principal);
    } else {
        searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
    }

    // Search for userDn and return.
    LdapContext systemLdapCtx = null;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        systemLdapCtx = getContextFactory().getSystemLdapContext();
        LOG.debug("Searching from " + searchBase + " with filter " + searchFilter);
        searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, SUBTREE_SCOPE);
        // SearchResults contains all the entries in search scope
        if (searchResultEnum.hasMore()) {
            SearchResult searchResult = searchResultEnum.next();
            userDn = searchResult.getNameInNamespace();
            LOG.debug("Found user DN: " + userDn);
            return userDn;
        } else {
            throw new IllegalArgumentException("Illegal principal name: " + principal);
        }
    } catch (AuthenticationException e) {
        throw new IllegalArgumentException("Illegal principal name: " + principal);
    } catch (NamingException e) {
        throw new IllegalArgumentException("Hit NamingException: " + e.getMessage());
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } catch (NamingException e) {
            // Ignore exception on close.
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
}

From source file:org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm.java

License:Apache License

private Set<String> getRoles(PrincipalCollection principals, final LdapContextFactory ldapContextFactory)
        throws NamingException {
    final String username = (String) getAvailablePrincipal(principals);

    LdapContext systemLdapCtx = null;
    try {//from  ww  w  .  jav  a 2 s .com
        systemLdapCtx = ldapContextFactory.getSystemLdapContext();
        return rolesFor(principals, username, systemLdapCtx, ldapContextFactory);
    } catch (AuthenticationException e) {
        LOG.failedToGetSystemLdapConnection(e);
        return Collections.emptySet();
    } finally {
        LdapUtils.closeContext(systemLdapCtx);
    }
}

From source file:org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm.java

License:Apache License

boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
        final LdapContextFactory ldapContextFactory) throws NamingException {

    // ldap://host:port/dn?attributes?scope?filter?extensions

    boolean member = false;

    if (memberUrl == null) {
        return false;
    }//from w  ww .ja  v a2s .  c  o m
    String[] tokens = memberUrl.split("\\?");
    if (tokens.length < 4) {
        return false;
    }

    String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
    String searchScope = tokens[2];
    String searchFilter = tokens[3];

    LdapName searchBaseDn = new LdapName(searchBaseString);

    // do scope test
    if (searchScope.equalsIgnoreCase("base")) {
        return false;
    }
    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
        return false;
    }
    if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) {
        return false;
    }
    // search for the filter, substituting base with userDn
    // search for base_dn=userDn, scope=base, filter=filter
    LdapContext systemLdapCtx = null;
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
        if (searchResultEnum.hasMore()) {
            return true;
        }
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
    return member;
}

From source file:org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm.java

License:Apache License

/**
   * Returns the LDAP User Distinguished Name (DN) to use when acquiring an
   * {@link javax.naming.ldap.LdapContext LdapContext} from the {@link LdapContextFactory}.
   * <p/>/*from   w  ww .  j a  va 2s  . c  om*/
   * If the the {@link #getUserDnTemplate() userDnTemplate} property has been set, this implementation will construct
   * the User DN by substituting the specified {@code principal} into the configured template.  If the
   * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method argument will be returned directly
   * (indicating that the submitted authentication token principal <em>is</em> the User DN).
   *
   * @param principal the principal to substitute into the configured {@link #getUserDnTemplate() userDnTemplate}.
   * @return the constructed User DN to use at runtime when acquiring an {@link javax.naming.ldap.LdapContext}.
   * @throws IllegalArgumentException if the method argument is null or empty
   * @throws IllegalStateException    if the {@link #getUserDnTemplate userDnTemplate} has not been set.
   * @see LdapContextFactory#getLdapContext(Object, Object)
   */
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
    String userDn;
    Matcher matchedPrincipal = matchPrincipal(principal);
    String userSearchBase = getUserSearchBase();
    String userSearchAttributeName = getUserSearchAttributeName();

    // If not searching use the userDnTemplate and return.
    if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null
            && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
        userDn = expandTemplate(userDnTemplate, matchedPrincipal);
        LOG.computedUserDn(userDn, principal);
        return userDn;
    }

    // Create the searchBase and searchFilter from config.
    String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
    String searchFilter = null;
    if (userSearchFilter == null) {
        if (userSearchAttributeName == null) {
            searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
        } else {
            searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(),
                    userSearchAttributeName,
                    expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal));
        }
    } else {
        searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
    }
    SearchControls searchControls = getUserSearchControls();

    // Search for userDn and return.
    LdapContext systemLdapCtx = null;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        systemLdapCtx = getContextFactory().getSystemLdapContext();
        LOG.searchBaseFilterScope(searchBase, searchFilter, userSearchScope);
        searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
        // SearchResults contains all the entries in search scope
        if (searchResultEnum.hasMore()) {
            SearchResult searchResult = searchResultEnum.next();
            userDn = searchResult.getNameInNamespace();
            LOG.searchedAndFoundUserDn(userDn, principal);
            return userDn;
        } else {
            throw new IllegalArgumentException("Illegal principal name: " + principal);
        }
    } catch (AuthenticationException e) {
        LOG.failedToGetSystemLdapConnection(e);
        throw new IllegalArgumentException("Illegal principal name: " + principal);
    } catch (NamingException e) {
        throw new IllegalArgumentException("Hit NamingException: " + e.getMessage());
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } catch (NamingException e) {
            // Ignore exception on close.
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
}

From source file:org.apache.isis.security.shiro.IsisLdapRealm.java

License:Apache License

private Set<String> getRoles(final PrincipalCollection principals, final LdapContextFactory ldapContextFactory)
        throws NamingException {
    final String username = (String) getAvailablePrincipal(principals);

    LdapContext systemLdapCtx = null;
    try {/*from ww  w .  ja  v a  2 s  .  c o  m*/
        systemLdapCtx = ldapContextFactory.getSystemLdapContext();
        return rolesFor(username, systemLdapCtx);
    } catch (AuthenticationException ex) {
        // principal was not authenticated on LDAP
        return Collections.emptySet();
    } finally {
        LdapUtils.closeContext(systemLdapCtx);
    }
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

License:Apache License

/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for
 * the specified username.  This method binds to the LDAP server using the provided username
 * and password - which if successful, indicates that the password is correct.
 * <p/>//from  w w  w  . j  a va 2s .c o  m
 * This method can be overridden by subclasses to query the LDAP server in a more complex way.
 *
 * @param token              the authentication token provided by the user.
 * @param ldapContextFactory the factory used to build connections to the LDAP server.
 * @return an {@link AuthenticationInfo} instance containing information retrieved from LDAP.
 * @throws NamingException if any LDAP errors occur during the search.
 */
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
        LdapContextFactory ldapContextFactory) throws NamingException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;

    // Binds using the username and password provided by the user.
    LdapContext ctx = null;
    try {
        String userPrincipalName = upToken.getUsername();
        if (!isValidPrincipalName(userPrincipalName)) {
            return null;
        }
        if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
            userPrincipalName = upToken.getUsername() + this.principalSuffix;
        }
        ctx = ldapContextFactory.getLdapContext(userPrincipalName, upToken.getPassword());
    } finally {
        LdapUtils.closeContext(ctx);
    }

    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

License:Apache License

/**
 * Builds an {@link org.apache.shiro.authz.AuthorizationInfo} object by querying the active
 * directory LDAP context for the groups that a user is a member of.  The groups are then
 * translated to role names by using the configured {@link #groupRolesMap}.
 * <p/>/*from  w  w  w .  j ava 2 s .c  om*/
 * This implementation expects the <tt>principal</tt> argument to be a String username.
 * <p/>
 * Subclasses can override this method to determine authorization data (roles, permissions, etc)
 * in a more complex way.  Note that this default implementation does not support permissions,
 * only roles.
 *
 * @param principals         the principal of the Subject whose account is being retrieved.
 * @param ldapContextFactory the factory used to create LDAP connections.
 * @return the AuthorizationInfo for the given Subject principal.
 * @throws NamingException if an error occurs when searching the LDAP server.
 */
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
        LdapContextFactory ldapContextFactory) throws NamingException {
    String username = (String) getAvailablePrincipal(principals);

    // Perform context search
    LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();

    Set<String> roleNames;

    try {
        roleNames = getRoleNamesForUser(username, ldapContext);
    } finally {
        LdapUtils.closeContext(ldapContext);
    }

    return buildAuthorizationInfo(roleNames);
}