org.ldaptive.LdapEntry Java Examples

The following examples show how to use org.ldaptive.LdapEntry. 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: MembershipSelector.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public LdapEntry next() {
  final String dn = dnsIterator.next();
  final SearchRequest request = new SearchRequest();
  request.setBaseDn(dn);
  request.setSearchFilter(usersFilter);
  request.setSearchScope(OBJECT);
  request.setReturnAttributes(returnAttrs);
  request.setSearchEntryHandlers(new ObjectGuidHandler());
  try {
    final Response<SearchResult> response = searchOp.execute(request);
    if (response.getResultCode() != SUCCESS) {
      throw new SyncException(
          format(
              "Couldn't get entry dn '%s', result code is '%s'", dn, response.getResultCode()));
    }
    return response.getResult().getEntry();
  } catch (LdapException x) {
    throw new SyncException(x.getLocalizedMessage(), x);
  }
}
 
Example #2
Source File: LDAPAuthorizationBackend.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private String getRoleFromEntry(final Connection ldapConnection, final LdapName ldapName, final String role) {

        if (ldapName == null || Strings.isNullOrEmpty(role)) {
            return null;
        }

        if("dn".equalsIgnoreCase(role)) {
            return ldapName.toString();
        }

        try {
            final LdapEntry roleEntry = LdapHelper.lookup(ldapConnection, ldapName.toString());

            if(roleEntry != null) {
                final LdapAttribute roleAttribute = roleEntry.getAttribute(role);
                if(roleAttribute != null) {
                    return Utils.getSingleStringValue(roleAttribute);
                }
            }
        } catch (LdapException e) {
            log.error("Unable to handle role {} because of ",ldapName, e.toString(), e);
        }

        return null;
    }
 
Example #3
Source File: LdapBackendTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdapAuthenticationReferral() throws Exception {


    final Settings settings = Settings.builder()
            .putList(ConfigConstants.LDAP_HOSTS, "localhost:" + ldapPort)
            .put(ConfigConstants.LDAP_AUTHC_USERSEARCH, "(uid={0})").build();

    final Connection con = LDAPAuthorizationBackend.getConnection(settings, null);
    try {
        final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST");
        Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn());
    } finally {
        con.close();
    }

}
 
Example #4
Source File: LdapBackendTestNewStyleConfig.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdapAuthenticationReferral() throws Exception {

    final Settings settings = Settings.builder()
            .putList(ConfigConstants.LDAP_HOSTS, "localhost:" + ldapPort)
            .put("users.u1.search", "(uid={0})").build();

    final Connection con = LDAPAuthorizationBackend.getConnection(settings, null);
    try {
        final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST");
        Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn());
    } finally {
        con.close();
    }

}
 
Example #5
Source File: LdapBackendTestNewStyleConfig2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdapAuthenticationReferral() throws Exception {

    final Settings settings = createBaseSettings()
            .putList(ConfigConstants.LDAP_HOSTS, "localhost:" + ldapPort)
            .put("users.u1.search", "(uid={0})").build();

    final Connection con = new LDAPConnectionFactoryFactory(settings, null).createBasicConnectionFactory()
            .getConnection();
    try {
        con.open();
        final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST");
        Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn());
    } finally {
        con.close();
    }

}
 
Example #6
Source File: LDAPAuthorizationBackend2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private String getRoleFromEntry(final Connection ldapConnection, final LdapName ldapName, final String role) {

        if (ldapName == null || Strings.isNullOrEmpty(role)) {
            return null;
        }

        if("dn".equalsIgnoreCase(role)) {
            return ldapName.toString();
        }

        try {
            final LdapEntry roleEntry = LdapHelper.lookup(ldapConnection, ldapName.toString());

            if(roleEntry != null) {
                final LdapAttribute roleAttribute = roleEntry.getAttribute(role);
                if(roleAttribute != null) {
                    return Utils.getSingleStringValue(roleAttribute);
                }
            }
        } catch (LdapException e) {
            log.error("Unable to handle role {} because of ",ldapName, e.toString(), e);
        }

        return null;
    }
 
Example #7
Source File: LdapBackendTestOldStyleConfig2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdapAuthenticationReferral() throws Exception {

    final Settings settings = createBaseSettings()
            .putList(ConfigConstants.LDAP_HOSTS, "localhost:" + ldapPort)
            .put(ConfigConstants.LDAP_AUTHC_USERSEARCH, "(uid={0})").build();

    final Connection con = new LDAPConnectionFactoryFactory(settings, null).createBasicConnectionFactory()
            .getConnection();
    try {
        con.open();
        final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST");
        Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn());
    } finally {
        con.close();
    }

}
 
Example #8
Source File: MembershipSelectorTest.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testMembershipSelection() throws Exception {
  final MembershipSelector selector =
      new MembershipSelector(
          server.getBaseDn(),
          "(objectClass=groupOfNames)",
          "(objectClass=inetOrgPerson)",
          "member",
          "uid",
          "givenName");
  try (Connection conn = connFactory.getConnection()) {
    conn.open();
    final Set<LdapEntry> selection =
        StreamSupport.stream(selector.select(conn).spliterator(), false).collect(toSet());
    assertEquals(selection.size(), 200);
    for (LdapEntry entry : selection) {
      assertNotNull(entry.getAttribute("givenName"));
      assertNotNull(entry.getAttribute("uid"));
    }
  }
}
 
Example #9
Source File: LdapUtils.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Reads a String value from the LdapEntry.
 *
 * @param entry       the ldap entry
 * @param attribute the attribute name
 * @param nullValue the value which should be returning in case of a null value
 * @return the string
 */
public static String getString(final LdapEntry entry, final String attribute, final String nullValue) {
    final LdapAttribute attr = entry.getAttribute(attribute);
    if (attr == null) {
        return nullValue;
    }

    String v = null;
    if (attr.isBinary()) {
        final byte[] b = attr.getBinaryValue();
        v = new String(b, Charset.forName("UTF-8"));
    } else {
        v = attr.getStringValue();
    }

    if (StringUtils.isNotBlank(v)) {
        return v;
    }
    return nullValue;
}
 
Example #10
Source File: LdapServiceRegistryDao.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public RegisteredService save(final RegisteredService rs) {
    if (rs.getId() != RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        return update(rs);
    }

    Connection connection = null;
    try {
        connection = getConnection();
        final AddOperation operation = new AddOperation(connection);

        final LdapEntry entry = this.ldapServiceMapper.mapFromRegisteredService(this.searchRequest.getBaseDn(), rs);
        operation.execute(new AddRequest(entry.getDn(), entry.getAttributes()));
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return rs;
}
 
Example #11
Source File: LdapServiceRegistryDao.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public List<RegisteredService> load() {
    Connection connection = null;
    final List<RegisteredService> list = new LinkedList<>();
    try {
        connection = getConnection();
        final Response<SearchResult> response =
                executeSearchOperation(connection, new SearchFilter(this.loadFilter));
        if (hasResults(response)) {
            for (final LdapEntry entry : response.getResult().getEntries()) {
                final RegisteredService svc = this.ldapServiceMapper.mapToRegisteredService(entry);
                list.add(svc);
            }
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return list;
}
 
Example #12
Source File: LdapAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyAuthenticateSuccess() throws Exception {
    for (final LdapEntry entry : this.getEntries()) {
        final String username = getUsername(entry);
        final String psw = entry.getAttribute("userPassword").getStringValue();
        final HandlerResult result = this.handler.authenticate(
                new UsernamePasswordCredential(username, psw));
        assertNotNull(result.getPrincipal());
        assertEquals(username, result.getPrincipal().getId());
        assertEquals(
                entry.getAttribute("displayName").getStringValue(),
                result.getPrincipal().getAttributes().get("displayName"));
        assertEquals(
                entry.getAttribute("mail").getStringValue(),
                result.getPrincipal().getAttributes().get("mail"));
    }
}
 
Example #13
Source File: LdapTestUtils.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Reads an LDIF into a collection of LDAP entries. The components performs a simple property
 * replacement in the LDIF data where <pre>${ldapBaseDn}</pre> is replaced with the environment-specific base
 * DN.
 *
 * @param ldif LDIF resource, typically a file on filesystem or classpath.
 * @param baseDn The directory branch where the entry resides.
 *
 * @return LDAP entries contained in the LDIF.
 *
 * @throws IOException On IO errors reading LDIF.
 */
public static Collection<LdapEntry> readLdif(final InputStream ldif, final String baseDn) throws IOException {
    final StringBuilder builder = new StringBuilder();
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(ldif))) {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains(BASE_DN_PLACEHOLDER)) {
                builder.append(line.replace(BASE_DN_PLACEHOLDER, baseDn));
            } else {
                builder.append(line);
            }
            builder.append(NEWLINE);
        }
    }
    return new LdifReader(new StringReader(builder.toString())).read().getEntries();
}
 
Example #14
Source File: LdaptiveResourceCRLFetcher.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Downloads a CRL from given LDAP url.
 *
 * @param r the resource that is the ldap url.
 * @return the x 509 cRL
 * @throws Exception if connection to ldap fails, or attribute to get the revocation list is unavailable
 */
protected X509CRL fetchCRLFromLdap(final Object r) throws Exception {
    try {
        final String ldapURL = r.toString();
        logger.debug("Fetching CRL from ldap {}", ldapURL);

        final Response<SearchResult> result = performLdapSearch(ldapURL);
        if (result.getResultCode() == ResultCode.SUCCESS) {
            final LdapEntry entry = result.getResult().getEntry();
            final LdapAttribute attribute = entry.getAttribute();

            logger.debug("Located entry [{}]. Retrieving first attribute [{}]",
                    entry, attribute);
            return fetchX509CRLFromAttribute(attribute);
        } else {
            logger.debug("Failed to execute the search [{}]", result);
        }

        throw new CertificateException("Failed to establish a connection ldap and search.");

    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
        throw new CertificateException(e);
    }
}
 
Example #15
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public RegisteredService save(final RegisteredService rs) {
    if (rs.getId() != RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        return update(rs);
    }

    Connection connection = null;
    try {
        connection = this.connectionFactory.getConnection();
        final AddOperation operation = new AddOperation(connection);

        final LdapEntry entry = this.ldapServiceMapper.mapFromRegisteredService(this.searchRequest.getBaseDn(), rs);
        operation.execute(new AddRequest(entry.getDn(), entry.getAttributes()));
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return rs;
}
 
Example #16
Source File: LdapServiceRegistryDao.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public List<RegisteredService> load() {
    Connection connection = null;
    final List<RegisteredService> list = new LinkedList<RegisteredService>();
    try {
        connection = this.connectionFactory.getConnection();
        final Response<SearchResult> response =
                executeSearchOperation(connection, new SearchFilter(this.loadFilter));
        if (hasResults(response)) {
            for (final LdapEntry entry : response.getResult().getEntries()) {
                final RegisteredService svc = this.ldapServiceMapper.mapToRegisteredService(entry);
                list.add(svc);
            }
        }
    } catch (final LdapException e) {
        logger.error(e.getMessage(), e);
    } finally {
        LdapUtils.closeConnection(connection);
    }
    return list;
}
 
Example #17
Source File: LdapAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateSuccess() throws Exception {
    String username;
    for (final LdapEntry entry : this.testEntries) {
        username = getUsername(entry);
        final HandlerResult result = this.handler.authenticate(
                new UsernamePasswordCredential(username, LdapTestUtils.getPassword(entry)));
        assertNotNull(result.getPrincipal());
        assertEquals(username, result.getPrincipal().getId());
        assertEquals(
                entry.getAttribute("displayName").getStringValue(),
                result.getPrincipal().getAttributes().get("displayName"));
        assertEquals(
                entry.getAttribute("mail").getStringValue(),
                result.getPrincipal().getAttributes().get("mail"));
    }
}
 
Example #18
Source File: LdapAuthenticationHandlerTests.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateNotFound() throws Exception {
    if (!this.supportsNotFound) {
        return;
    }
    String username;
    for (final LdapEntry entry : this.testEntries) {
        username = getUsername(entry);
        try {
            this.handler.authenticate(new UsernamePasswordCredential("nobody", "badpassword"));
            fail("Should have thrown AccountNotFoundException.");
        } catch (final AccountNotFoundException e) {
            assertNotNull(e.getMessage());
        }
    }
}
 
Example #19
Source File: LdapTestUtils.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Reads an LDIF into a collection of LDAP entries. The components performs a simple property
 * replacement in the LDIF data where <pre>${ldapBaseDn}</pre> is replaced with the environment-specific base
 * DN.
 *
 * @param ldif LDIF resource, typically a file on filesystem or classpath.
 * @param baseDn The directory branch where the entry resides.
 *
 * @return LDAP entries contained in the LDIF.
 *
 * @throws IOException On IO errors reading LDIF.
 */
public static Collection<LdapEntry> readLdif(final Resource ldif, final String baseDn) throws IOException {
    final StringBuilder builder = new StringBuilder();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(ldif.getInputStream()));
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains(BASE_DN_PLACEHOLDER)) {
                builder.append(line.replace(BASE_DN_PLACEHOLDER, baseDn));
            } else {
                builder.append(line);
            }
            builder.append(NEWLINE);
        }
    } finally {
        reader.close();
    }
    return new LdifReader(new StringReader(builder.toString())).read().getEntries();
}
 
Example #20
Source File: DefaultLdapRegisteredServiceMapper.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public LdapEntry mapFromRegisteredService(final String dn, final RegisteredService svc) {
    try {
        if (svc.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) {
            ((AbstractRegisteredService) svc).setId(System.nanoTime());
        }
        final String newDn = getDnForRegisteredService(dn, svc);
        LOGGER.debug("Creating entry {}", newDn);

        final Collection<LdapAttribute> attrs = new ArrayList<>();
        attrs.add(new LdapAttribute(this.idAttribute, String.valueOf(svc.getId())));

        final StringWriter writer = new StringWriter();
        this.jsonSerializer.toJson(writer, svc);
        attrs.add(new LdapAttribute(this.serviceDefinitionAttribute, writer.toString()));
        attrs.add(new LdapAttribute(LdapUtils.OBJECTCLASS_ATTRIBUTE, "top", this.objectClass));

        return new LdapEntry(newDn, attrs);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: LDAPUserSearcher.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private LdapEntry existsSearchingUntilFirstHit(Connection ldapConnection, String user) throws Exception {
    final String username = user;

    for (Map.Entry<String, Settings> entry : userBaseSettings) {
        Settings baseSettings = entry.getValue();

        SearchFilter f = new SearchFilter();
        f.setFilter(baseSettings.get(ConfigConstants.LDAP_AUTHCZ_SEARCH, DEFAULT_USERSEARCH_PATTERN));
        f.setParameter(ZERO_PLACEHOLDER, username);

        List<LdapEntry> result = LdapHelper.search(ldapConnection,
                baseSettings.get(ConfigConstants.LDAP_AUTHCZ_BASE, DEFAULT_USERBASE),
                f,
                SearchScope.SUBTREE);

        if (log.isDebugEnabled()) {
            log.debug("Results for LDAP search for " + user + " in base " + entry.getKey() + ":\n" + result);
        }

        if (result != null && result.size() >= 1) {
            return result.get(0);
        }
    }

    return null;
}
 
Example #22
Source File: LdapUserService.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticates the username and password using the LDAP/AD service. By default all the users
 * authenticated will have <b>USER</b> role. We might change this in future depending on the
 * attribute info available in the LDAP entries.
 *
 * @param userName ldap username
 * @param password ldap password
 * @param domain Auth domain.
 * @return {@link OneOpsUser} details object if successfully authenticated, else returns <code>
 *     null</code>.
 * @throws LdapException throws if any error authenticating/connecting to ldap server.
 */
public @Nullable OneOpsUser authenticate(String userName, char[] password, AuthDomain domain)
    throws LdapException {
  LdapEntry ldapUser =
      metricService.time("oneops.ldap.auth", () -> ldapClient.authenticate(userName, password));

  if (ldapUser != null) {
    String cn = getCommonName(ldapUser, userName);
    return new OneOpsUser(
        userName,
        String.valueOf(password),
        singletonList(new SimpleGrantedAuthority(USER.authority())),
        cn,
        domain);
  }
  return null;
}
 
Example #23
Source File: DefaultLdapServiceMapper.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private Collection<String> getMultiValuedAttributeValues(@NotNull final LdapEntry entry, @NotNull final String attrName) {
    final LdapAttribute attrs = entry.getAttribute(attrName);
    if (attrs != null) {
        return attrs.getStringValues();
    }
    return Collections.emptyList();
}
 
Example #24
Source File: DefaultLdapServiceMapper.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public RegisteredService mapToRegisteredService(final LdapEntry entry) {

    final LdapAttribute attr = entry.getAttribute(this.serviceIdAttribute);

    if (attr != null) {
        final AbstractRegisteredService s = getRegisteredService(attr.getStringValue());

        if (s != null) {
            s.setId(LdapUtils.getLong(entry, this.idAttribute, Long.valueOf(entry.getDn().hashCode())));

            s.setServiceId(LdapUtils.getString(entry, this.serviceIdAttribute));
            s.setName(LdapUtils.getString(entry, this.serviceNameAttribute));
            s.setDescription(LdapUtils.getString(entry, this.serviceDescriptionAttribute));
            s.setEnabled(LdapUtils.getBoolean(entry, this.serviceEnabledAttribute));
            s.setTheme(LdapUtils.getString(entry, this.serviceThemeAttribute));
            s.setEvaluationOrder(LdapUtils.getLong(entry, this.evaluationOrderAttribute).intValue());
            s.setUsernameAttribute(LdapUtils.getString(entry, this.usernameAttribute));
            s.setAllowedToProxy(LdapUtils.getBoolean(entry, this.serviceAllowedToProxyAttribute));
            s.setAnonymousAccess(LdapUtils.getBoolean(entry, this.serviceAnonymousAccessAttribute));
            s.setSsoEnabled(LdapUtils.getBoolean(entry, this.serviceSsoEnabledAttribute));
            s.setAllowedAttributes(new ArrayList<String>(getMultiValuedAttributeValues(entry, this.serviceAllowedAttributesAttribute)));
            s.setIgnoreAttributes(LdapUtils.getBoolean(entry, this.ignoreAttributesAttribute));
            s.setRequiredHandlers(new HashSet<String>(getMultiValuedAttributeValues(entry, this.requiredHandlersAttribute)));
        }
        return s;
    }
    return null;
}
 
Example #25
Source File: DefaultLdapServiceMapper.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public LdapEntry mapFromRegisteredService(final String dn, final RegisteredService svc) {


    if (svc.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) {
        ((AbstractRegisteredService) svc).setId(System.nanoTime());
    }
    final String newDn = getDnForRegisteredService(dn, svc);
    LOGGER.debug("Creating entry {}", newDn);

    final Collection<LdapAttribute> attrs = new ArrayList<LdapAttribute>();
    attrs.add(new LdapAttribute(this.idAttribute, String.valueOf(svc.getId())));
    attrs.add(new LdapAttribute(this.serviceIdAttribute, svc.getServiceId()));
    attrs.add(new LdapAttribute(this.serviceNameAttribute, svc.getName()));
    attrs.add(new LdapAttribute(this.serviceDescriptionAttribute, svc.getDescription()));
    attrs.add(new LdapAttribute(this.serviceEnabledAttribute, Boolean.toString(svc.isEnabled()).toUpperCase()));
    attrs.add(new LdapAttribute(this.serviceAllowedToProxyAttribute, Boolean.toString(svc.isAllowedToProxy()).toUpperCase()));
    attrs.add(new LdapAttribute(this.serviceAnonymousAccessAttribute, Boolean.toString(svc.isAnonymousAccess()).toUpperCase()));
    attrs.add(new LdapAttribute(this.serviceSsoEnabledAttribute, Boolean.toString(svc.isSsoEnabled()).toUpperCase()));
    attrs.add(new LdapAttribute(this.ignoreAttributesAttribute, Boolean.toString(svc.isAnonymousAccess()).toUpperCase()));
    attrs.add(new LdapAttribute(this.evaluationOrderAttribute, String.valueOf(svc.getEvaluationOrder())));
    attrs.add(new LdapAttribute(this.serviceThemeAttribute, svc.getTheme()));
    attrs.add(new LdapAttribute(this.usernameAttribute, svc.getUsernameAttribute()));

    if (svc.getAllowedAttributes().size() > 0) {
        attrs.add(new LdapAttribute(this.serviceAllowedAttributesAttribute, svc.getAllowedAttributes().toArray(new String[] {})));
    }

    if (svc.getRequiredHandlers().size() > 0) {
        attrs.add(new LdapAttribute(this.requiredHandlersAttribute, svc.getRequiredHandlers().toArray(new String[] {})));
    }

    attrs.add(new LdapAttribute(LdapUtils.OBJECTCLASS_ATTRIBUTE, this.objectClass));

    return new LdapEntry(newDn, attrs);
}
 
Example #26
Source File: LdapUserIdNormalizerTest.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void shouldRetrieveIdValueAndNormalizeIt() {
  final String id = "{123}";
  final LdapEntry entry = new LdapEntry("uid=user123", new LdapAttribute("uid", id));

  final String normalizedId = idNormalizer.retrieveAndNormalize(entry);

  assertEquals(normalizedId, "123");
  assertEquals(entry.getAttribute("uid").getStringValue(), "{123}");
}
 
Example #27
Source File: LdapUser.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public LdapUser(final String name, String originalUsername, final LdapEntry userEntry,
        final AuthCredentials credentials, int customAttrMaxValueLen, List<String> whiteListedAttributes) {
    super(name, null, credentials);
    this.originalUsername = originalUsername;
    this.userEntry = userEntry;
    Map<String, String> attributes = getCustomAttributesMap();
    attributes.putAll(extractLdapAttributes(originalUsername, userEntry, customAttrMaxValueLen, whiteListedAttributes));
}
 
Example #28
Source File: LdapSpec.java    From bdt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param groupCn The new group
 * @throws LdapException
 * @throws NoSuchAlgorithmException
 */
@When("^I create LDAP group '(.+?)'$")
public void createLDAPGroup(String groupCn) throws LdapException {
    String groupDn = "cn=" + groupCn + "," + ThreadProperty.get("LDAP_GROUP_DN");
    int groupGidNumber = this.commonspec.getLdapUtils().getLDAPMaxGidNumber() + 1;

    LdapEntry newGroup = new LdapEntry(groupDn);
    newGroup.addAttribute(new LdapAttribute("objectClass", "groupOfNames", "posixGroup"));
    newGroup.addAttribute(new LdapAttribute("cn", groupCn));
    newGroup.addAttribute(new LdapAttribute("gidNumber", String.valueOf(groupGidNumber)));
    newGroup.addAttribute(new LdapAttribute("member", "uid=fake," + ThreadProperty.get("LDAP_USER_DN")));
    newGroup.addAttribute(new LdapAttribute("description", groupCn + " group"));
    newGroup.addAttribute(new LdapAttribute("memberUid", "uid=fake," + ThreadProperty.get("LDAP_USER_DN")));
    this.commonspec.getLdapUtils().add(newGroup);
}
 
Example #29
Source File: LdapAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
 *
 * @param username Username that was successfully authenticated which is used for principal ID when
 *                 {@link #setPrincipalIdAttribute(String)} is not specified.
 * @param ldapEntry LDAP entry that may contain principal attributes.
 *
 * @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
 *
 * @throws LoginException On security policy errors related to principal creation.
 */
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
    final String id;
    if (this.principalIdAttribute != null) {
        final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
        if (principalAttr == null || principalAttr.size() == 0) {
            throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
        }
        if (principalAttr.size() > 1) {
            if (this.allowMultiplePrincipalAttributeValues) {
                logger.warn(
                        "Found multiple values for principal ID attribute: {}. Using first value={}.",
                        principalAttr,
                        principalAttr.getStringValue());
            } else {
                throw new LoginException("Multiple principal values not allowed: " + principalAttr);
            }
        }
        id = principalAttr.getStringValue();
    } else {
        id = username;
    }
    final Map<String, Object> attributeMap = new LinkedHashMap<>(this.principalAttributeMap.size());
    for (final Map.Entry<String, String> ldapAttr : this.principalAttributeMap.entrySet()) {
        final LdapAttribute attr = ldapEntry.getAttribute(ldapAttr.getKey());
        if (attr != null) {
            logger.debug("Found principal attribute: {}", attr);
            final String principalAttrName = ldapAttr.getValue();
            if (attr.size() > 1) {
                attributeMap.put(principalAttrName, attr.getStringValues());
            } else {
                attributeMap.put(principalAttrName, attr.getStringValue());
            }
        }
    }
    return this.principalFactory.createPrincipal(id, attributeMap);
}
 
Example #30
Source File: LdapUserIdNormalizerTest.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void shouldModifyLdapEntryByNormalizingIdAttribute() {
  final String id = "{123}";
  final LdapEntry entry = new LdapEntry("uid=user123", new LdapAttribute("uid", id));

  idNormalizer.normalize(entry);

  assertEquals(entry.getAttribute("uid").getStringValue(), "123");
}