public void initialize() { try { this.workManager = (WorkManager) new InitialContext().lookup(workManagerName); } catch (NamingException e) { throw new IllegalStateException("Could not locate WorkManager: " + e.getMessage(), e); } }
public void initialize() { try { this.workManager = (WorkManager) new InitialContext().lookup(workManagerName); } catch (NamingException e) { throw new IllegalStateException("Could not locate WorkManager: " + e.getMessage(), e); } }
/** * Closes given resource logging possible checked exception. * * @param rsrc Resource to close. If it's {@code null} - it's no-op. * @param log Logger to log possible checked exception with (optional). */ public static void close(@Nullable Context rsrc, @Nullable IgniteLogger log) { if (rsrc != null) try { rsrc.close(); } catch (NamingException e) { warn(log, "Failed to close resource: " + e.getMessage()); } }
if (logger.isDebugEnabled()) { logger.debug("JNDI lookup for name [" + name + "] threw NamingException " + "with message: " + ex.getMessage() + ". Returning null.");
public boolean authenticateUser(String ldapUrl, String username, String password, String domains) { String[] domainArr = domains.split(","); for (String domain : domainArr) { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, domain + "\\" + username); env.put(Context.SECURITY_CREDENTIALS, password); try { ctx = new InitialDirContext(env); return true; } catch (NamingException e) { } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException ex) { logger.warn(ex.getMessage()); } } } } return false; } }
private void checkForGroupMembership(String user, DirContext context) { if (!groupAuthorizationSearchPattern.isPresent()) { return; } String userBase = userBaseDistinguishedName.orElseThrow(VerifyException::new); String searchFilter = replaceUser(groupAuthorizationSearchPattern.get(), user); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); boolean authorized; try { NamingEnumeration<SearchResult> search = context.search(userBase, searchFilter, searchControls); authorized = search.hasMoreElements(); search.close(); } catch (NamingException e) { log.debug("Authentication error for user [%s]: %s", user, e.getMessage()); throw new RuntimeException("Authentication error"); } if (!authorized) { String message = format("User [%s] not a member of the authorized group", user); log.debug(message); throw new AccessDeniedException(message); } }
if (logger.isDebugEnabled()) { logger.debug("JNDI lookup for name [" + name + "] threw NamingException " + "with message: " + ex.getMessage() + ". Returning null.");
private void handleBindException(String bindPrincipal, NamingException exception) { if (logger.isDebugEnabled()) { logger.debug("Authentication for " + bindPrincipal + " failed:" + exception); } handleResolveObj(exception); int subErrorCode = parseSubErrorCode(exception.getMessage()); if (subErrorCode <= 0) { logger.debug("Failed to locate AD-specific sub-error code in message"); return; } logger.info("Active Directory authentication failed: " + subCodeToLogMessage(subErrorCode)); if (convertSubErrorCodesToExceptions) { raiseExceptionForErrorCode(subErrorCode, exception); } }
public JndiDataSourceProvider(String dsName, String jndiName, String dialect, boolean showSql) { this.dsName = dsName; Context ctx; try { ctx = new InitialContext(); ds = (DataSource) ctx.lookup(jndiName); if (ds == null) { throw new DBException("Jndi could not found error for " + jndiName); } } catch (NamingException e) { throw new DBException(e.getMessage(), e); } this.dialect = DialectFactory.get(dialect == null ? "mysql" : dialect); this.showSql = showSql; }
protected List<Address> resolveSRVEntries(String dnsQuery) { List<Address> addresses = new ArrayList<>(); try { // We are parsing this kind of structure: // {srv=SRV: 10 100 8888 9089f34a.jgroups-dns-ping.myproject.svc.cluster.local.} // The frst attribute is the type of record. We are not interested in this. Next are addresses. Attributes attributes = dnsContext.getAttributes(dnsQuery, new String[] { DNSRecordType.SRV.toString() }); if (attributes != null && attributes.getAll().hasMoreElements()) { NamingEnumeration<?> namingEnumeration = attributes.get(DNSRecordType.SRV.toString()).getAll(); while (namingEnumeration.hasMoreElements()) { try { String srvEntry = namingEnumeration.nextElement().toString(); Matcher matcher = SRV_REGEXP.matcher(srvEntry); if (matcher.find()) { String srcPort = matcher.group(1); String srcDNSRecord = matcher.group(2); // The implementation here is not optimal but it's easy to read. SRV discovery will be performed // extremely rarely, only when a fine grained discovery using ports is needed (ie: when using containers). addresses.addAll(resolveAEntries(srcDNSRecord, srcPort)); } } catch (Exception e) { log.trace("non critical DNS resolution error", e); } } } } catch (NamingException ex) { log.trace("no DNS records for query %s, ex: %s", dnsQuery, ex.getMessage()); } return addresses; }
@Test public void testLookupWithExpectedTypeAndNoMatch() throws Exception { JndiObjectFactoryBean jof = new JndiObjectFactoryBean(); jof.setJndiTemplate(new ExpectedLookupTemplate("foo", new Object())); jof.setJndiName("foo"); jof.setExpectedType(String.class); try { jof.afterPropertiesSet(); fail("Should have thrown NamingException"); } catch (NamingException ex) { assertTrue(ex.getMessage().contains("java.lang.String")); } }
private void raiseExceptionForErrorCode(int code, NamingException exception) { String hexString = Integer.toHexString(code); Throwable cause = new ActiveDirectoryAuthenticationException(hexString, exception.getMessage(), exception); switch (code) { case PASSWORD_EXPIRED: throw new CredentialsExpiredException(messages.getMessage( "LdapAuthenticationProvider.credentialsExpired", "User credentials have expired"), cause); case ACCOUNT_DISABLED: throw new DisabledException(messages.getMessage( "LdapAuthenticationProvider.disabled", "User is disabled"), cause); case ACCOUNT_EXPIRED: throw new AccountExpiredException(messages.getMessage( "LdapAuthenticationProvider.expired", "User account has expired"), cause); case ACCOUNT_LOCKED: throw new LockedException(messages.getMessage( "LdapAuthenticationProvider.locked", "User account is locked"), cause); default: throw badCredentials(cause); } }
@Test public void testLookupWithProxyInterfaceAndExpectedTypeAndNoMatch() { JndiObjectFactoryBean jof = new JndiObjectFactoryBean(); TestBean tb = new TestBean(); jof.setJndiTemplate(new ExpectedLookupTemplate("foo", tb)); jof.setJndiName("foo"); jof.setExpectedType(DerivedTestBean.class); jof.setProxyInterface(ITestBean.class); try { jof.afterPropertiesSet(); fail("Should have thrown NamingException"); } catch (NamingException ex) { assertTrue(ex.getMessage().contains("org.springframework.tests.sample.beans.DerivedTestBean")); } }
private void closeContext(final LdapContext context) { try { if (context != null) { context.close(); } } catch (final NamingException e) { s_logger.warn(e.getMessage(), e); } }
private void checkForGroupMembership(String user, DirContext context) { if (!groupAuthorizationSearchPattern.isPresent()) { return; } String searchFilter = replaceUser(groupAuthorizationSearchPattern.get(), user); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); boolean authorized; NamingEnumeration<SearchResult> search = null; try { search = context.search(userBaseDistinguishedName.get(), searchFilter, searchControls); authorized = search.hasMoreElements(); } catch (NamingException e) { log.debug("Authentication failed", e.getMessage()); throw new RakamException("Authentication failed: " + e.getMessage(), INTERNAL_SERVER_ERROR); } finally { if (search != null) { try { search.close(); } catch (NamingException ignore) { } } } if (!authorized) { String message = format("Unauthorized user: User %s not a member of the authorized group", user); log.debug("Authorization failed for user. " + message); throw new RakamException(message, UNAUTHORIZED); } log.debug("Authorization succeeded for user %s", user); }
@Override public List<LdapUser> getUsersInGroup(String groupName, LdapContext context, Long domainId) throws NamingException { String attributeName = _ldapConfiguration.getGroupUniqueMemberAttribute(domainId); final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(new String[] {attributeName}); NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(domainId), generateGroupSearchFilter(groupName, domainId), controls); final List<LdapUser> users = new ArrayList<LdapUser>(); //Expecting only one result which has all the users if (result.hasMoreElements()) { Attribute attribute = result.nextElement().getAttributes().get(attributeName); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMoreElements()) { String userdn = String.valueOf(values.nextElement()); try{ users.add(getUserForDn(userdn, context, domainId)); } catch (NamingException e){ s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); } } } Collections.sort(users); return users; }
throw new DnsException(ne.getMessage()); } catch (Exception e) { throw new DnsException(e.getMessage());
public Connection getConnection() throws SQLException { Connection conn = null; try { if (dataSource == null) { dataSource = lookupDataSource(); } if(getUser() != null) { addWarn("Ignoring property [user] with value ["+getUser()+"] for obtaining a connection from a DataSource."); } conn = dataSource.getConnection(); } catch (final NamingException ne) { addError("Error while getting data source", ne); throw new SQLException("NamingException while looking up DataSource: " + ne.getMessage()); } catch (final ClassCastException cce) { addError("ClassCastException while looking up DataSource.", cce); throw new SQLException("ClassCastException while looking up DataSource: " + cce.getMessage()); } return conn; }
} catch (NamingException e) { throw new SQLException("P6DataSource: naming exception during jndi lookup of Real Data Source Name of '" + rdsName + "'. " + e.getMessage(), e);
public Principal authenticate(String user, String password) throws RakamException { Map<String, String> environment = createEnvironment(user, password); InitialDirContext context; try { context = createDirContext(environment); checkForGroupMembership(user, context); log.debug("Authentication successful for user %s", user); return new LdapPrincipal(user); } catch (javax.naming.AuthenticationException e) { String formattedAsciiMessage = format("Invalid credentials: %s", JAVA_ISO_CONTROL.removeFrom(e.getMessage())); log.debug("Authentication failed for user [%s]. %s", user, e.getMessage()); throw new RakamException(formattedAsciiMessage, UNAUTHORIZED); } catch (NamingException e) { log.debug("Authentication failed", e.getMessage()); throw new RakamException("Authentication failed", INTERNAL_SERVER_ERROR); } }