use of org.forgerock.opendj.ldap.Connection in project OpenAM by OpenRock.
the class LocalLdapAuthModule method authenticate.
private boolean authenticate(String dn, String passwd) throws LoginException {
// LDAP connection used for authentication
Connection localConn = null;
String host;
int port;
Options ldapOptions = Options.defaultOptions();
// Check if organization is present in options
String orgUrl = (String) options.get(LoginContext.ORGNAME);
if ((orgUrl == null) || (orgUrl.equals(LoginContext.LDAP_AUTH_URL)) || (orgUrl.equals(LoginContext.LDAPS_AUTH_URL)) || !(orgUrl.startsWith(LoginContext.LDAP_AUTH_URL) || orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL))) {
try {
DSConfigMgr dscm = DSConfigMgr.getDSConfigMgr();
// We need a handle on server instance so we can know the
// Connection type. If it is SSL, the connection needs to be
// accordingly created. Note: The user type does not make
// a difference, as the connection type is Server group based,
// so passing any user type for the second argument.
ServerInstance si = dscm.getServerInstance(DSConfigMgr.DEFAULT, LDAPUser.Type.AUTH_BASIC);
String hostName = dscm.getHostName(DSConfigMgr.DEFAULT);
if (si.getConnectionType() == Server.Type.CONN_SSL) {
try {
ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
} catch (GeneralSecurityException e) {
debug.error("getConnection.JSSESocketFactory", e);
throw new LDAPServiceException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_JSSSFFAIL));
}
}
if (dn != null && passwd != null) {
// The 389 port number passed is overridden by the
// hostName:port
// constructed by the getHostName method. So, this is not
// a hardcoded port number.
host = hostName;
port = 389;
} else {
// Throw LoginException
throw new LoginException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_CONNECTFAIL));
}
} catch (LDAPServiceException ex) {
debug.error("Authenticate failed: " + ex);
throw new LoginException(ex.getMessage());
}
} else {
try {
if (debug.messageEnabled()) {
debug.message("authenticate(): orgUrl= " + orgUrl);
}
// Get hostname
int start;
boolean useSSL = false;
if (orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL)) {
start = LoginContext.LDAPS_AUTH_URL.length();
useSSL = true;
} else {
start = LoginContext.LDAP_AUTH_URL.length();
}
int end = orgUrl.indexOf(':', start);
if (end == -1) {
end = orgUrl.indexOf('/', start);
if (end == -1)
end = orgUrl.length();
}
String hostName = orgUrl.substring(start, end);
// Get port number
String portNumber = "389";
start = end + 1;
if (start < orgUrl.length()) {
end = orgUrl.indexOf('/', start);
if (end == -1)
end = orgUrl.length();
portNumber = orgUrl.substring(start, end);
}
if (useSSL) {
try {
ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
} catch (GeneralSecurityException e) {
debug.error("authentication().JSSESocketFactory()", e);
throw (new LoginException(e.getMessage()));
}
}
if (debug.messageEnabled()) {
debug.message("before connect(), hostName=" + hostName + ",port=" + portNumber);
}
host = hostName;
port = Integer.parseInt(portNumber);
} catch (Exception e) {
debug.error("authentication", e);
throw (new LoginException(e.getMessage()));
}
}
try (ConnectionFactory factory = LDAPUtils.createFailoverConnectionFactory(host, port, dn, passwd, ldapOptions);
Connection conn = factory.getConnection()) {
return true;
} catch (LdapException e) {
throw new LoginException(e.getMessage());
}
}
use of org.forgerock.opendj.ldap.Connection in project ddf by codice.
the class SslLdapLoginModule method doLogin.
protected boolean doLogin() throws LoginException {
//--------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
try {
callbackHandler.handle(callbacks);
} catch (IOException ioException) {
throw new LoginException(ioException.getMessage());
} catch (UnsupportedCallbackException unsupportedCallbackException) {
boolean result;
throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
}
user = ((NameCallback) callbacks[0]).getName();
if (user == null) {
return false;
}
user = user.trim();
validateUsername(user);
char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
// this method.
if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
// default to simple so that the provided user/password will get checked
setBindMethod(DEFAULT_AUTHENTICATION);
}
if (tmpPassword == null) {
tmpPassword = new char[0];
}
//---------------------------------------------------------------------
// RESET OBJECT STATE AND DECLARE LOCAL VARS
principals = new HashSet<>();
Connection connection;
String userDn;
//------------- CREATE CONNECTION #1 ----------------------------------
try {
connection = ldapConnectionFactory.getConnection();
} catch (LdapException e) {
LOGGER.info("Unable to get LDAP Connection from factory.", e);
return false;
}
if (connection != null) {
try {
//------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
try {
BindRequest request;
switch(getBindMethod()) {
case "Simple":
request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
break;
case "SASL":
request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
break;
case "GSSAPI SASL":
request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
((GSSAPISASLBindRequest) request).setRealm(realm);
((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
break;
case "Digest MD5 SASL":
request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
((DigestMD5SASLBindRequest) request).getQOPs().clear();
((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
if (StringUtils.isNotEmpty(realm)) {
((DigestMD5SASLBindRequest) request).setRealm(realm);
}
break;
default:
request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
break;
}
BindResult bindResult = connection.bind(request);
if (!bindResult.isSuccess()) {
LOGGER.debug("Bind failed");
return false;
}
} catch (LdapException e) {
LOGGER.debug("Unable to bind to LDAP server.", e);
return false;
}
//--------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
SearchScope scope;
if (userSearchSubtree) {
scope = SearchScope.WHOLE_SUBTREE;
} else {
scope = SearchScope.SINGLE_LEVEL;
}
userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
userFilter = userFilter.replace("\\", "\\\\");
ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter);
try {
if (!entryReader.hasNext()) {
LOGGER.info("User {} not found in LDAP.", user);
return false;
}
SearchResultEntry searchResultEntry = entryReader.readEntry();
userDn = searchResultEntry.getName().toString();
} catch (LdapException | SearchResultReferenceIOException e) {
LOGGER.info("Unable to read contents of LDAP user search.", e);
return false;
}
} finally {
//------------ CLOSE CONNECTION -------------------------------
connection.close();
}
} else {
return false;
}
//------------- CREATE CONNECTION #2 ----------------------------------
try {
connection = ldapConnectionFactory.getConnection();
} catch (LdapException e) {
LOGGER.info("Unable to get LDAP Connection from factory.", e);
return false;
}
if (connection != null) {
// Validate user's credentials.
try {
BindResult bindResult = connection.bind(userDn, tmpPassword);
if (!bindResult.isSuccess()) {
LOGGER.info("Bind failed");
return false;
}
} catch (Exception e) {
LOGGER.info("Unable to bind user to LDAP server.", e);
return false;
} finally {
//------------ CLOSE CONNECTION -------------------------------
connection.close();
}
//---------- ADD USER AS PRINCIPAL --------------------------------
principals.add(new UserPrincipal(user));
} else {
return false;
}
//-------------- CREATE CONNECTION #3 ---------------------------------
try {
connection = ldapConnectionFactory.getConnection();
} catch (LdapException e) {
LOGGER.info("Unable to get LDAP Connection from factory.", e);
return false;
}
if (connection != null) {
try {
//----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
try {
BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
if (!bindResult.isSuccess()) {
LOGGER.info("Bind failed");
return false;
}
} catch (LdapException e) {
LOGGER.info("Unable to bind to LDAP server.", e);
return false;
}
//--------- SEARCH #3, GET ROLES ------------------------------
SearchScope scope;
if (roleSearchSubtree) {
scope = SearchScope.WHOLE_SUBTREE;
} else {
scope = SearchScope.SINGLE_LEVEL;
}
roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
roleFilter = roleFilter.replace("\\", "\\\\");
ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute);
SearchResultEntry entry;
//------------- ADD ROLES AS NEW PRINCIPALS -------------------
try {
while (entryReader.hasNext()) {
entry = entryReader.readEntry();
Attribute attr = entry.getAttribute(roleNameAttribute);
for (ByteString role : attr) {
principals.add(new RolePrincipal(role.toString()));
}
}
} catch (Exception e) {
boolean result;
throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
}
} finally {
//------------ CLOSE CONNECTION -------------------------------
connection.close();
}
} else {
return false;
}
return true;
}
use of org.forgerock.opendj.ldap.Connection in project ddf by codice.
the class SslLdapLoginModuleTest method testUnsuccessfulConnectionBind1.
@Test
public void testUnsuccessfulConnectionBind1() throws LoginException {
LDAPConnectionFactory mockedConnectionFactory = PowerMockito.mock(LDAPConnectionFactory.class);
BindResult mockedBindResult = mock(BindResult.class);
when(mockedBindResult.isSuccess()).thenReturn(false);
Connection mockedConnection = mock(Connection.class);
SslLdapLoginModule testLoginModule = mock(SslLdapLoginModule.class);
try {
when(mockedConnectionFactory.getConnection()).thenReturn(mockedConnection);
when(mockedConnection.bind(anyString(), any(char[].class))).thenReturn(mockedBindResult);
when(testLoginModule.createLdapConnectionFactory(any(String.class), any(Boolean.class))).thenReturn(mockedConnectionFactory);
} catch (LdapException e) {
LOGGER.debug("LDAP exception", e);
}
Boolean loginBool = testLoginModule.doLogin();
assertThat(loginBool, is(false));
}
use of org.forgerock.opendj.ldap.Connection in project admin-console-beta by connexta.
the class LdapTestingUtils method bindUserToLdapConnection.
/**
* Binds the user to the LDAP connection.
*
* Possible message types: CANNOT_CONFIGURE, CANNOT_CONNECT, CANNOT_BIND
* @param connField
* @param bindInfo
* @return
*/
public LdapConnectionAttempt bindUserToLdapConnection(LdapConnectionField connField, LdapBindUserInfo bindInfo) {
LdapConnectionAttempt connectionAttempt = getLdapConnection(connField);
if (!connectionAttempt.connection().isPresent()) {
return connectionAttempt;
}
Connection connection = connectionAttempt.connection().get();
try {
BindRequest bindRequest = selectBindMethod(bindInfo.bindMethod(), bindInfo.credentials().username(), bindInfo.credentials().password(), bindInfo.realm(), null);
connection.bind(bindRequest);
} catch (Exception e) {
LOGGER.debug("Error binding to LDAP", e);
return new LdapConnectionAttempt(CANNOT_BIND);
}
return new LdapConnectionAttempt(connection);
}
use of org.forgerock.opendj.ldap.Connection in project admin-console-beta by connexta.
the class LdapTestingUtils method getLdapConnection.
/**
* Attempts to connect to the given ldap address given the hostname, port, and encryptionMethod
*
* Possible message types: CANNOT_CONFIGURE, CANNOT_CONNECT
* @return
*/
public LdapConnectionAttempt getLdapConnection(LdapConnectionField connection) {
LDAPOptions ldapOptions = new LDAPOptions();
try {
if (connection.encryptionMethod().equals(LDAPS)) {
ldapOptions.setSSLContext(SSLContext.getDefault());
} else if (connection.encryptionMethod().equals(START_TLS)) {
ldapOptions.setUseStartTLS(true);
}
ldapOptions.addEnabledCipherSuite(System.getProperty("https.cipherSuites").split(","));
ldapOptions.addEnabledProtocol(System.getProperty("https.protocols").split(","));
//sets the classloader so it can find the grizzly protocol handler class
ldapOptions.setProviderClassLoader(LdapTestingUtils.class.getClassLoader());
} catch (Exception e) {
LOGGER.debug("Error prepping LDAP connection", e);
return new LdapConnectionAttempt(CANNOT_CONFIGURE);
}
Connection ldapConnection;
try {
ldapConnection = new LDAPConnectionFactory(connection.hostname(), connection.port(), ldapOptions).getConnection();
} catch (Exception e) {
LOGGER.debug("Error opening LDAP connection to [{}:{}]", connection.hostname(), connection.port());
return new LdapConnectionAttempt(CANNOT_CONNECT);
}
return new LdapConnectionAttempt(ldapConnection);
}
Aggregations