Java Code Examples for org.apache.shiro.realm.ldap.LdapContextFactory#getSystemLdapContext()

The following examples show how to use org.apache.shiro.realm.ldap.LdapContextFactory#getSystemLdapContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * 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/>
 * 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);
}
 
Example 2
Source File: LdapRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private Set<String> getRoles(PrincipalCollection principals,
        final LdapContextFactory ldapContextFactory) throws NamingException {
  final String username = (String) getAvailablePrincipal(principals);

  LdapContext systemLdapCtx = null;
  try {
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    return rolesFor(principals, username, systemLdapCtx,
      ldapContextFactory, SecurityUtils.getSubject().getSession());
  } catch (Throwable t) {
    log.warn("Failed to get roles in current context for " + username, t);
    return Collections.emptySet();
  } finally {
    LdapUtils.closeContext(systemLdapCtx);
  }
}
 
Example 3
Source File: SearchFirstActiveDirectoryRealm.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the
 * specified username.
 *
 * @return the DN of the user, or {@code null} if there's no such user
 */
@Nullable
protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException {
    LdapContext ctx = null;
    try {
        // Binds using the system username and password.
        ctx = ldapContextFactory.getSystemLdapContext();

        final SearchControls ctrl = new SearchControls();
        ctrl.setCountLimit(1);
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setTimeLimit(searchTimeoutMillis);

        final String filter =
                searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter)
                                                           .replaceAll(username)
                                     : username;
        final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl);
        try {
            if (!result.hasMore()) {
                return null;
            }
            return result.next().getNameInNamespace();
        } finally {
            result.close();
        }
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
 
Example 4
Source File: LdapGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
        LdapContextFactory ldapContextFactory) throws NamingException {
  String username = (String) getAvailablePrincipal(principals);
  LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
  Set<String> roleNames = getRoleNamesForUser(username, ldapContext, getUserDnTemplate());
  return new SimpleAuthorizationInfo(roleNames);
}
 
Example 5
Source File: KnoxLdapRealm.java    From knox with Apache License 2.0 5 votes vote down vote up
private Set<String> getRoles(PrincipalCollection principals,
    final LdapContextFactory ldapContextFactory) throws NamingException {
    final String username = (String) getAvailablePrincipal(principals);

    LdapContext systemLdapCtx = null;
    try {
        systemLdapCtx = ldapContextFactory.getSystemLdapContext();
        return rolesFor(principals, username, systemLdapCtx, ldapContextFactory);
    } catch (AuthenticationException e) {
      LOG.failedToGetSystemLdapConnection(e);
      return Collections.emptySet();
    } finally {
        LdapUtils.closeContext(systemLdapCtx);
    }
}
 
Example 6
Source File: GreenStepBaseAuthorizingActiveDirectoryCustomQueryAttributeRealm.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
    final GreenStepBaseUsernamePasswordToken usernamePasswordToken = (GreenStepBaseUsernamePasswordToken) token;
    LdapContext ctx = null;
    /*
    try {
    	ctx = ldapContextFactory.getSystemLdapContext();
        final String attribName = "userPrincipalName";
        final SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { attribName }, false, false);
        final NamingEnumeration<SearchResult> search = ctx.search(searchBase, this.getCustomQueryAttributeValue(), new Object[] { usernamePasswordToken.getPrincipal() }, searchControls);
        if (search.hasMore()) {
        	final SearchResult next = search.next();
            String loginUser= next.getAttributes().get(attribName).get().toString();
            if (search.hasMore()) {
                throw new RuntimeException("More than one user matching: "+usernamePasswordToken.getPrincipal());
            } else {
                try {
                	ldapContextFactory.getLdapContext(loginUser, usernamePasswordToken.getPassword());
                } catch (Exception ex) {
                    throw ex;
                }
            }
        }
        else {
            throw new RuntimeException("No user matching: " + usernamePasswordToken.getPrincipal());
        }
    } catch (NamingException ne) {
        throw ne;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    */
    String searchBaseArr[] = StringUtils.defaultString(searchBase).split( Constants.ID_DELIMITER );
    boolean searchUser = false;
    for (int i = 0; searchBaseArr != null && !searchUser && i<searchBaseArr.length; i++) {
        try {
        	ctx = ldapContextFactory.getSystemLdapContext();
            final String attribName = "userPrincipalName";
            final SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { attribName }, false, false);
            final NamingEnumeration<SearchResult> search = ctx.search(searchBaseArr[i], this.getCustomQueryAttributeValue(), new Object[] { usernamePasswordToken.getPrincipal() }, searchControls);
            if (search.hasMore()) {
            	searchUser = true;
            	final SearchResult next = search.next();
                String loginUser= next.getAttributes().get(attribName).get().toString();
                if (search.hasMore()) {
                    throw new RuntimeException("More than one user matching: "+usernamePasswordToken.getPrincipal());
                } else {
                    try {
                    	ldapContextFactory.getLdapContext(loginUser, usernamePasswordToken.getPassword());
                    } catch (Exception ex) {
                        throw ex;
                    }
                }
            }
            /*
            else {
                throw new RuntimeException("No user matching: " + usernamePasswordToken.getPrincipal());
            }
            */
        } catch (NamingException ne) {
            throw ne;
        } finally {
            LdapUtils.closeContext(ctx);
        }        	
    }
    if (!searchUser) {
    	throw new RuntimeException("No user matching: " + usernamePasswordToken.getPrincipal());
    }        
    return buildAuthenticationInfo(usernamePasswordToken.getUsername(), usernamePasswordToken.getPassword());
}
 
Example 7
Source File: LdapRealm.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
    final LdapContextFactory ldapContextFactory) throws NamingException {
  // ldap://host:port/dn?attributes?scope?filter?extensions
  if (memberUrl == null) {
    return false;
  }
  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 ("base".equalsIgnoreCase(searchScope)) {
    log.debug("DynamicGroup SearchScope base");
    return false;
  }
  if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
    return false;
  }
  if ("one".equalsIgnoreCase(searchScope) && (userLdapDn.size() != searchBaseDn.size() - 1)) {
    log.debug("DynamicGroup SearchScope one");
    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();
  boolean member = false;
  NamingEnumeration<SearchResult> searchResultEnum = null;
  try {
    searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                                            "sub".equalsIgnoreCase(searchScope) ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
    if (searchResultEnum.hasMore()) {
      return true;
    }
  } finally {
    try {
      if (searchResultEnum != null) {
        searchResultEnum.close();
      }
    } finally {
      LdapUtils.closeContext(systemLdapCtx);
    }
  }
  return member;
}
 
Example 8
Source File: KnoxLdapRealm.java    From knox with Apache License 2.0 4 votes vote down vote up
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;
  }
  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 ("base".equalsIgnoreCase(searchScope)) {
    return false;
  }
  if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
    return false;
  }
  if ("one".equalsIgnoreCase(searchScope)
      && (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;
  systemLdapCtx = ldapContextFactory.getSystemLdapContext();
  NamingEnumeration<SearchResult> searchResultEnum = null;
  try {
    searchResultEnum = systemLdapCtx
      .search(userLdapDn, searchFilter,
          "sub".equalsIgnoreCase(searchScope) ? SUBTREE_SCOPE
              : ONELEVEL_SCOPE);
    if (searchResultEnum.hasMore()) {
      return true;
    }
  }
  finally {
      try {
        if (searchResultEnum != null) {
          searchResultEnum.close();
        }
      }
      finally {
        LdapUtils.closeContext(systemLdapCtx);
      }
  }
  return member;
}