use of org.apache.directory.ldap.client.api.LdapConnection in project jackrabbit-oak by apache.
the class LdapIdentityProvider method getIdentity.
@Override
public ExternalIdentity getIdentity(@Nonnull ExternalIdentityRef ref) throws ExternalIdentityException {
if (!isMyRef(ref)) {
return null;
}
LdapConnection connection = connect();
try {
String userIdAttr = config.getUserConfig().getIdAttribute();
String groupIdAttr = config.getGroupConfig().getIdAttribute();
String[] ca = config.getCustomAttributes();
Entry entry;
if (ca.length == 0) {
entry = connection.lookup(ref.getId(), SchemaConstants.ALL_USER_ATTRIBUTES);
} else {
List<String> attributes = new ArrayList<>(Arrays.asList(ca));
attributes.add("objectClass");
attributes.add(userIdAttr);
attributes.add(groupIdAttr);
String[] attributeArray = new String[attributes.size()];
attributes.toArray(attributeArray);
entry = connection.lookup(ref.getId(), attributeArray);
}
if (entry == null) {
return null;
} else if (entry.hasObjectClass(config.getUserConfig().getObjectClasses())) {
return createUser(entry, null);
} else if (entry.hasObjectClass(config.getGroupConfig().getObjectClasses())) {
return createGroup(entry, null);
} else {
log.warn("referenced identity is neither user or group: {}", ref.getString());
return null;
}
} catch (LdapException e) {
throw lookupFailedException(e, null);
} finally {
disconnect(connection);
}
}
use of org.apache.directory.ldap.client.api.LdapConnection in project jackrabbit-oak by apache.
the class LdapIdentityProvider method authenticate.
@Override
public ExternalUser authenticate(@Nonnull Credentials credentials) throws ExternalIdentityException, LoginException {
if (!(credentials instanceof SimpleCredentials)) {
log.debug("LDAP IDP can only authenticate SimpleCredentials.");
return null;
}
final SimpleCredentials creds = (SimpleCredentials) credentials;
final ExternalUser user = getUser(creds.getUserID());
if (user != null) {
// see http://tools.ietf.org/html/rfc4513#section-5.1.1 for details.
if (creds.getPassword().length == 0) {
throw new LoginException("Refusing to authenticate against LDAP server: Empty passwords not allowed.");
}
// authenticate
LdapConnection connection = null;
try {
DebugTimer timer = new DebugTimer();
if (userPool == null) {
connection = userConnectionFactory.makeObject();
} else {
connection = userPool.getConnection();
}
timer.mark("connect");
connection.bind(user.getExternalId().getId(), new String(creds.getPassword()));
timer.mark("bind");
if (log.isDebugEnabled()) {
log.debug("authenticate({}) {}", user.getId(), timer.getString());
}
} catch (LdapAuthenticationException e) {
throw new LoginException("Unable to authenticate against LDAP server: " + e.getMessage());
} catch (Exception e) {
throw new ExternalIdentityException("Error while binding user credentials", e);
} finally {
if (connection != null) {
try {
if (userPool == null) {
userConnectionFactory.destroyObject(connection);
} else {
userPool.releaseConnection(connection);
}
} catch (Exception e) {
// ignore
}
}
}
}
return user;
}
use of org.apache.directory.ldap.client.api.LdapConnection in project karaf by apache.
the class LdapSpecialCharsInPasswordTest method changeAdminPassword.
@Before
public void changeAdminPassword() throws Exception {
LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort());
connection.bind("uid=admin,ou=system", "secret");
Dn adminDn = new Dn("uid=admin,ou=system");
ModifyRequest modReq = new ModifyRequestImpl();
modReq.setName(adminDn);
modReq.replace(SchemaConstants.USER_PASSWORD_AT, NEW_CONNECTION_PASSWORD);
connection.modify(modReq);
connection.close();
// check that we actually changed the admin connection password
connection = new LdapNetworkConnection("localhost", getLdapServer().getPort());
connection.bind("uid=admin,ou=system", NEW_CONNECTION_PASSWORD);
connection.close();
}
use of org.apache.directory.ldap.client.api.LdapConnection in project mxisd by kamax-io.
the class LdapAuthProvider method authenticate.
@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
log.info("Performing auth for {}", mxid);
try (LdapConnection conn = getConn()) {
bind(conn);
String uidType = getAt().getUid().getType();
String userFilterValue = StringUtils.equals(LdapBackend.UID, uidType) ? mxid.getLocalPart() : mxid.getId();
if (StringUtils.isBlank(userFilterValue)) {
log.warn("Username is empty, failing auth");
return BackendAuthResult.failure();
}
String userFilter = "(" + getUidAtt() + "=" + userFilterValue + ")";
userFilter = buildWithFilter(userFilter, getCfg().getAuth().getFilter());
Set<String> attributes = new HashSet<>();
attributes.add(getUidAtt());
attributes.add(getAt().getName());
getAt().getThreepid().forEach((k, v) -> attributes.addAll(v));
String[] attArray = new String[attributes.size()];
attributes.toArray(attArray);
log.debug("Base DN: {}", getBaseDn());
log.debug("Query: {}", userFilter);
log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
try (EntryCursor cursor = conn.search(getBaseDn(), userFilter, SearchScope.SUBTREE, attArray)) {
while (cursor.next()) {
Entry entry = cursor.get();
String dn = entry.getDn().getName();
log.info("Checking possible match, DN: {}", dn);
if (!getAttribute(entry, getUidAtt()).isPresent()) {
continue;
}
log.info("Attempting authentication on LDAP for {}", dn);
try {
conn.bind(entry.getDn(), password);
} catch (LdapException e) {
log.info("Unable to bind using {} because {}", entry.getDn().getName(), e.getMessage());
return BackendAuthResult.failure();
}
Attribute nameAttribute = entry.get(getAt().getName());
String name = nameAttribute != null ? nameAttribute.get().toString() : null;
log.info("Authentication successful for {}", entry.getDn().getName());
log.info("DN {} is a valid match", dn);
// TODO should we canonicalize the MXID?
BackendAuthResult result = BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, name);
log.info("Processing 3PIDs for profile");
getAt().getThreepid().forEach((k, v) -> {
log.info("Processing 3PID type {}", k);
v.forEach(attId -> {
List<String> values = getAttributes(entry, attId);
log.info("\tAttribute {} has {} value(s)", attId, values.size());
getAttributes(entry, attId).forEach(tpidValue -> {
if (ThreePidMedium.PhoneNumber.is(k)) {
tpidValue = getMsisdn(tpidValue).orElse(tpidValue);
}
result.withThreePid(new ThreePid(k, tpidValue));
});
});
});
log.info("Found {} 3PIDs", result.getProfile().getThreePids().size());
return result;
}
} catch (CursorLdapReferralException e) {
log.warn("Entity for {} is only available via referral, skipping", mxid);
}
log.info("No match were found for {}", mxid);
return BackendAuthResult.failure();
} catch (LdapException | IOException | CursorException e) {
throw new RuntimeException(e);
}
}
use of org.apache.directory.ldap.client.api.LdapConnection in project mxisd by kamax-io.
the class LdapDirectoryProvider method search.
protected UserDirectorySearchResult search(String query, List<String> attributes) {
UserDirectorySearchResult result = new UserDirectorySearchResult();
result.setLimited(false);
try (LdapConnection conn = getConn()) {
bind(conn);
LdapConfig.Attribute atCfg = getCfg().getAttribute();
attributes = new ArrayList<>(attributes);
attributes.add(getUidAtt());
String[] attArray = new String[attributes.size()];
attributes.toArray(attArray);
String searchQuery = buildOrQueryWithFilter(getCfg().getDirectory().getFilter(), "*" + query + "*", attArray);
log.debug("Base DN: {}", getBaseDn());
log.debug("Query: {}", searchQuery);
log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
try (EntryCursor cursor = conn.search(getBaseDn(), searchQuery, SearchScope.SUBTREE, attArray)) {
while (cursor.next()) {
Entry entry = cursor.get();
log.info("Found possible match, DN: {}", entry.getDn().getName());
getAttribute(entry, getUidAtt()).ifPresent(uid -> {
log.info("DN {} is a valid match", entry.getDn().getName());
try {
UserDirectorySearchResult.Result entryResult = new UserDirectorySearchResult.Result();
entryResult.setUserId(buildMatrixIdFromUid(uid));
getAttribute(entry, atCfg.getName()).ifPresent(entryResult::setDisplayName);
result.addResult(entryResult);
} catch (IllegalArgumentException e) {
log.warn("Bind was found but type {} is not supported", atCfg.getUid().getType());
}
});
}
}
} catch (CursorLdapReferralException e) {
log.warn("An entry is only available via referral, skipping");
} catch (IOException | LdapException | CursorException e) {
throw new InternalServerError(e);
}
return result;
}
Aggregations