org.apache.shiro.realm.ldap.LdapUtils Java Examples

The following examples show how to use org.apache.shiro.realm.ldap.LdapUtils. 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: LdapRealm.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken authenticationToken,
                                                        LdapContextFactory ldapContextFactory) throws NamingException {
    String token = (String) authenticationToken.getCredentials();
    // 解密获得username,用于和数据库进行对比
    String username = JwtUtil.getUsername(token);

    if (null==username  || !JwtUtil.verify(token, username)) {
        throw new AuthenticationException("token认证失败!");
    }
    LdapContext ctx = null;
    try {
        ctx = ldapContextFactory.getLdapContext(username, null);
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return new SimpleAuthenticationInfo(token, token, "MyRealm");
}
 
Example #2
Source File: SearchFirstActiveDirectoryRealm.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Nullable
private AuthenticationInfo queryForAuthenticationInfo0(
        AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

    final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token);
    final String userDn = findUserDn(ldapContextFactory, upToken.getUsername());
    if (userDn == null) {
        return null;
    }

    LdapContext ctx = null;
    try {
        // Binds using the username and password provided by the user.
        ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword());
    } catch (AuthenticationException e) {
        // According to this page, LDAP error code 49 (invalid credentials) is the only case where
        // AuthenticationException is raised:
        // - https://docs.oracle.com/javase/tutorial/jndi/ldap/exceptions.html
        // - com.sun.jndi.ldap.LdapCtx.mapErrorCode()
        return null;
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
 
Example #3
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * 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/>
 * 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());
}
 
Example #4
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 #5
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 #6
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 #7
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public List<String> searchForUserName(String containString, LdapContext ldapContext,
    int numUsersToFetch)
        throws NamingException {
  List<String> userNameList = new ArrayList<>();

  SearchControls searchCtls = new SearchControls();
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  searchCtls.setCountLimit(numUsersToFetch);

  String searchFilter = String.format("(&(objectClass=*)(%s=*%s*))", this.getUserSearchAttributeName(), containString);

  Object[] searchArguments = new Object[]{containString};

  NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
      searchCtls);

  while (answer.hasMoreElements()) {
    SearchResult sr = (SearchResult) answer.next();

    if (log.isDebugEnabled()) {
      log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
    }

    Attributes attrs = sr.getAttributes();
    if (attrs != null) {
      NamingEnumeration ae = attrs.getAll();
      while (ae.hasMore()) {
        Attribute attr = (Attribute) ae.next();
        if (attr.getID().toLowerCase().equals(this.getUserSearchAttributeName().toLowerCase())) {
          userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
        }
      }
    }
  }
  return userNameList;
}
 
Example #8
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 #9
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 #10
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext)
        throws NamingException {
  Set<String> roleNames = new LinkedHashSet<>();

  SearchControls searchCtls = new SearchControls();
  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  String userPrincipalName = username;
  if (this.principalSuffix != null && userPrincipalName.indexOf('@') > 1) {
    userPrincipalName = userPrincipalName.split("@")[0];
  }

  String searchFilter = String.format("(&(objectClass=*)(%s=%s))", this.getUserSearchAttributeName(), userPrincipalName);
  Object[] searchArguments = new Object[]{userPrincipalName};

  NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
      searchCtls);

  while (answer.hasMoreElements()) {
    SearchResult sr = (SearchResult) answer.next();

    if (log.isDebugEnabled()) {
      log.debug("Retrieving group names for user [" + sr.getName() + "]");
    }

    Attributes attrs = sr.getAttributes();

    if (attrs != null) {
      NamingEnumeration ae = attrs.getAll();
      while (ae.hasMore()) {
        Attribute attr = (Attribute) ae.next();

        if (attr.getID().equals("memberOf")) {

          Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

          if (log.isDebugEnabled()) {
            log.debug("Groups found for user [" + username + "]: " + groupNames);
          }

          Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
          roleNames.addAll(rolesForGroups);
        }
      }
    }
  }
  return roleNames;
}
 
Example #11
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 #12
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;
}