Java源码示例:org.ldaptive.Connection
示例1
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;
}
示例2
private void authenticateByLdapServer(final Connection connection, final String dn, byte[] password)
throws LdapException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Response<Void>>() {
@Override
public Response<Void> run() throws LdapException {
return connection.getProviderConnection().bind(new BindRequest(dn, new Credential(password)));
}
});
} catch (PrivilegedActionException e) {
if (e.getException() instanceof LdapException) {
throw (LdapException) e.getException();
} else if (e.getException() instanceof RuntimeException) {
throw (RuntimeException) e.getException();
} else {
throw new RuntimeException(e);
}
}
}
示例3
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;
}
示例4
public static void unbindAndCloseSilently(final Connection connection) {
if (connection == null) {
return;
}
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
connection.close();
return null;
}
});
} catch (PrivilegedActionException e) {
// ignore
}
}
示例5
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;
}
示例6
@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();
}
}
示例7
@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();
}
}
示例8
@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();
}
}
示例9
@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();
}
}
示例10
/**
* Gets a connection from the underlying connection factory and attempts to validate it.
*
* @return Status with code {@link StatusCode#OK} on success otherwise {@link StatusCode#ERROR}.
*/
@Override
public Status observe() {
Connection conn = null;
try {
conn = this.connectionFactory.getConnection();
if (!conn.isOpen()) {
conn.open();
}
return this.validator.validate(conn) ? OK : ERROR;
} catch (final LdapException e) {
logger.warn("Validation failed with error.", e);
} finally {
LdapUtils.closeConnection(conn);
}
return ERROR;
}
示例11
@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;
}
示例12
@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;
}
示例13
@Override
public RegisteredService findServiceById(final long id) {
Connection connection = null;
try {
connection = getConnection();
final Response<SearchResult> response = searchForServiceById(connection, id);
if (hasResults(response)) {
return this.ldapServiceMapper.mapToRegisteredService(response.getResult().getEntry());
}
} catch (final LdapException e) {
logger.error(e.getMessage(), e);
} finally {
LdapUtils.closeConnection(connection);
}
return null;
}
示例14
/**
* Gets a connection from the underlying connection factory and attempts to validate it.
*
* @return Status with code {@link StatusCode#OK} on success otherwise {@link StatusCode#ERROR}.
*/
@Override
public Status observe() {
Connection conn = null;
try {
conn = this.connectionFactory.getConnection();
if (!conn.isOpen()) {
conn.open();
}
return this.validator.validate(conn) ? OK : ERROR;
} catch (final LdapException e) {
logger.warn("Validation failed with error.", e);
} finally {
LdapUtils.closeConnection(conn);
}
return ERROR;
}
示例15
@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;
}
示例16
@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;
}
示例17
@Override
public RegisteredService findServiceById(final long id) {
Connection connection = null;
try {
connection = this.connectionFactory.getConnection();
final Response<SearchResult> response = searchForServiceById(connection, id);
if (hasResults(response)) {
return this.ldapServiceMapper.mapToRegisteredService(response.getResult().getEntry());
}
} catch (final LdapException e) {
logger.error(e.getMessage(), e);
} finally {
LdapUtils.closeConnection(connection);
}
return null;
}
示例18
@Before
public void setUp() throws Exception {
// Environment check
this.enableLdapTests = System.getProperty("enableLdapTests") != null;
Assume.assumeTrue("enableLdapTests system property not set", this.enableLdapTests);
this.context = new ClassPathXmlApplicationContext(this.contextPaths);
this.baseDn = this.context.getBean("baseDn", String.class);
this.usersLdif = this.context.getBean("usersLdif", Resource.class);
this.usernameAttribute = this.context.getBean("usernameAttribute", String.class);
this.provisioningConnectionFactory = this.context.getBean(
"provisioningConnectionFactory", ConnectionFactory.class);
this.testEntries = LdapTestUtils.readLdif(this.usersLdif, this.baseDn);
final Connection connection = getConnection();
try {
connection.open();
LdapTestUtils.createLdapEntries(connection, this.directoryType, this.testEntries);
} finally {
LdapUtils.closeConnection(connection);
}
}
示例19
@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"));
}
}
}
示例20
LdapEntry exists(Connection ldapConnection, String user) throws Exception {
if (settings.getAsBoolean(ConfigConstants.LDAP_FAKE_LOGIN_ENABLED, false)
|| settings.getAsBoolean(ConfigConstants.LDAP_SEARCH_ALL_BASES, false)
|| settings.hasValue(ConfigConstants.LDAP_AUTHC_USERBASE)) {
return existsSearchingAllBases(ldapConnection, user);
} else {
return existsSearchingUntilFirstHit(ldapConnection, user);
}
}
示例21
private LdapEntry existsSearchingAllBases(Connection ldapConnection, String user) throws Exception {
final String username = user;
Set<LdapEntry> result = new HashSet<>();
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> foundEntries = 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 (foundEntries != null) {
result.addAll(foundEntries);
}
}
if (result.isEmpty()) {
log.debug("No user " + username + " found");
return null;
}
if (result.size() > 1) {
log.debug("More than one user for '" + username + "' found");
return null;
}
return result.iterator().next();
}
示例22
public static LdapEntry lookup(final Connection conn, final String unescapedDn) throws LdapException {
final List<LdapEntry> entries = search(conn, unescapedDn, ALL, SearchScope.OBJECT);
if (entries.size() == 1) {
return entries.get(0);
} else {
return null;
}
}
示例23
public static Connection getConnection(final Settings settings, final Path configPath) throws Exception {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SpecialPermission());
}
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Connection>() {
@Override
public Connection run() throws Exception {
boolean isJava9OrHigher = PlatformDependent.javaVersion() >= 9;
ClassLoader originalClassloader = null;
if (isJava9OrHigher) {
originalClassloader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(new Java9CL());
}
return getConnection0(settings, configPath, originalClassloader, isJava9OrHigher);
}
});
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
示例24
static LdapEntry exists(final String user, Connection ldapConnection, Settings settings,
List<Map.Entry<String, Settings>> userBaseSettings) throws Exception {
if (settings.getAsBoolean(ConfigConstants.LDAP_FAKE_LOGIN_ENABLED, false)
|| settings.getAsBoolean(ConfigConstants.LDAP_SEARCH_ALL_BASES, false)
|| settings.hasValue(ConfigConstants.LDAP_AUTHC_USERBASE)) {
return existsSearchingAllBases(user, ldapConnection, userBaseSettings);
} else {
return existsSearchingUntilFirstHit(user, ldapConnection, userBaseSettings);
}
}
示例25
private static LdapEntry existsSearchingUntilFirstHit(final String user, Connection ldapConnection,
List<Map.Entry<String, Settings>> userBaseSettings) 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;
}
示例26
private static LdapEntry existsSearchingAllBases(final String user, Connection ldapConnection,
List<Map.Entry<String, Settings>> userBaseSettings) throws Exception {
final String username = user;
Set<LdapEntry> result = new HashSet<>();
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> foundEntries = 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 (foundEntries != null) {
result.addAll(foundEntries);
}
}
if (result.isEmpty()) {
log.debug("No user " + username + " found");
return null;
}
if (result.size() > 1) {
log.debug("More than one user for '" + username + "' found");
return null;
}
return result.iterator().next();
}
示例27
/**
* Close the given context and ignore any thrown exception. This is useful
* for typical finally blocks in manual Ldap statements.
*
* @param context the Ldap connection to close
*/
public static void closeConnection(final Connection context) {
if (context != null && context.isOpen()) {
try {
context.close();
} catch (final Exception ex) {
LOGGER.warn("Could not close ldap connection", ex);
}
}
}
示例28
@Override
protected StatusCode checkPool() throws Exception {
final Connection conn = this.connectionFactory.getConnection();
try {
return this.validator.validate(conn) ? StatusCode.OK : StatusCode.ERROR;
} finally {
LdapUtils.closeConnection(conn);
}
}
示例29
/**
* Execute search operation.
*
* @param connection the connection
* @param filter the filter
* @return the response
* @throws LdapException the ldap exception
*/
private Response<SearchResult> executeSearchOperation(final Connection connection, final SearchFilter filter)
throws LdapException {
final SearchOperation searchOperation = new SearchOperation(connection);
final SearchRequest request = newRequest(filter);
logger.debug("Using search request {}", request.toString());
return searchOperation.execute(request);
}
示例30
/**
* Gets connection from the factory.
* Opens the connection if needed.
*
* @return the connection
* @throws LdapException the ldap exception
*/
private Connection getConnection() throws LdapException {
final Connection c = this.connectionFactory.getConnection();
if (!c.isOpen()) {
c.open();
}
return c;
}