javax.naming.ldap.LdapContext Java Examples
The following examples show how to use
javax.naming.ldap.LdapContext.
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: AbstractFallbackRequestAndResponseControlDirContextProcessor.java From spring-ldap with Apache License 2.0 | 6 votes |
public void postProcess(DirContext ctx) throws NamingException { LdapContext ldapContext = (LdapContext) ctx; Control[] responseControls = ldapContext.getResponseControls(); if (responseControls == null) { responseControls = new Control[0]; } // Go through response controls and get info, regardless of class for (Control responseControl : responseControls) { // check for match, try fallback otherwise if (responseControl.getClass().isAssignableFrom(responseControlClass)) { handleResponse(responseControl); return; } } log.info("No matching response control found - looking for '" + responseControlClass); }
Example #2
Source File: LdapAuthentication.java From glowroot with Apache License 2.0 | 6 votes |
@Instrumentation.TraceEntry(message = "get ldap group DNs for user DN: {{1}}", timer = "ldap") private static Set<String> getGroupDnsForUserDn(LdapContext ldapContext, String userDn, LdapConfig ldapConfig) throws NamingException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.groupBaseDn(), ldapConfig.groupSearchFilter(), new String[] {userDn}, searchCtls); try { Set<String> ldapGroups = Sets.newHashSet(); while (namingEnum.hasMore()) { SearchResult result = (SearchResult) checkNotNull(namingEnum.next()); ldapGroups.add(result.getNameInNamespace()); } return ldapGroups; } finally { namingEnum.close(); } }
Example #3
Source File: LDAPLoginManagerImpl.java From olat with Apache License 2.0 | 6 votes |
private byte[] getCookie(final LdapContext ctx) throws NamingException, IOException { byte[] cookie = null; // Examine the paged results control response final Control[] controls = ctx.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; cookie = prrc.getCookie(); } } } // Re-activate paged results ctx.setRequestControls(new Control[] { new PagedResultsControl(PAGE_SIZE, cookie, Control.CRITICAL) }); return cookie; }
Example #4
Source File: LdapAuthentication.java From glowroot with Apache License 2.0 | 6 votes |
@Instrumentation.TraceEntry(message = "get ldap user DN for username: {{1}}", timer = "ldap") private static @Nullable String getUserDn(LdapContext ldapContext, String username, LdapConfig ldapConfig) throws NamingException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.userBaseDn(), ldapConfig.userSearchFilter(), new String[] {username}, searchCtls); try { if (!namingEnum.hasMore()) { return null; } SearchResult result = (SearchResult) checkNotNull(namingEnum.next()); String userDn = result.getNameInNamespace(); if (namingEnum.hasMore()) { throw new IllegalStateException("More than matching user: " + username); } return userDn; } finally { namingEnum.close(); } }
Example #5
Source File: LdapManagerImpl.java From cloudstack with Apache License 2.0 | 6 votes |
@Override public LdapUser getUser(final String username, final String type, final String name, Long domainId) throws NoLdapUserMatchingQueryException { LdapContext context = null; try { context = _ldapContextFactory.createBindContext(domainId); final String escapedUsername = LdapUtils.escapeLDAPSearchFilter(username); LdapUserManager.Provider ldapProvider = _ldapConfiguration.getLdapProvider(domainId); if (ldapProvider == null) { // feeble second attempt? ldapProvider = _ldapConfiguration.getLdapProvider(null); } LdapUserManager userManagerFactory = _ldapUserManagerFactory.getInstance(ldapProvider); return userManagerFactory.getUser(escapedUsername, type, name, context, domainId); } catch (NamingException | IOException e) { LOGGER.debug("ldap Exception: ",e); throw new NoLdapUserMatchingQueryException("No Ldap User found for username: "+username + " in group: " + name + " of type: " + type); } finally { closeContext(context); } }
Example #6
Source File: LdapConfigCheckMain.java From ranger with Apache License 2.0 | 6 votes |
private static void retrieveUsers(LdapContext ldapContext, UserSync userSyncObj) throws Throwable { String msg; if (userSyncObj.getUserNameAttribute() == null || userSyncObj.getUserNameAttribute().isEmpty()) { msg = "ranger.usersync.ldap.user.nameattribute "; throw new NullArgumentException(msg); } if (userSyncObj.getUserObjClassName() == null || userSyncObj.getUserObjClassName().isEmpty()) { msg = "ranger.usersync.ldap.user.objectclass "; throw new NullArgumentException(msg); } if ((userSyncObj.getUserSearchBase() == null || userSyncObj.getUserSearchBase().isEmpty()) && (userSyncObj.getSearchBase() == null || userSyncObj.getSearchBase().isEmpty())) { msg = "ranger.usersync.ldap.user.searchbase and " + "ranger.usersync.ldap.searchBase "; throw new NullArgumentException(msg); } userSyncObj.getAllUsers(ldapContext); }
Example #7
Source File: LdapConnector.java From projectforge-webapp with GNU General Public License v3.0 | 6 votes |
public LdapContext createContext() { init(); final Hashtable<String, String> env; final String authentication = ldapConfig.getAuthentication(); if ("none".equals(authentication) == false) { env = createEnv(ldapConfig.getManagerUser(), ldapConfig.getManagerPassword()); } else { env = createEnv(null, null); } try { final LdapContext ctx = new InitialLdapContext(env, null); return ctx; } catch (final NamingException ex) { log.error("While trying to connect LDAP initally: " + ex.getMessage(), ex); throw new RuntimeException(ex); } }
Example #8
Source File: LdapManagerImpl.java From cosmic with Apache License 2.0 | 6 votes |
@Override public LdapConfigurationResponse addConfiguration(final String hostname, final int port) throws InvalidParameterValueException { LdapConfigurationVO configuration = _ldapConfigurationDao.findByHostname(hostname); if (configuration == null) { LdapContext context = null; try { final String providerUrl = "ldap://" + hostname + ":" + port; context = _ldapContextFactory.createBindContext(providerUrl); configuration = new LdapConfigurationVO(hostname, port); _ldapConfigurationDao.persist(configuration); s_logger.info("Added new ldap server with hostname: " + hostname); return new LdapConfigurationResponse(hostname, port); } catch (NamingException | IOException e) { s_logger.debug("NamingException while doing an LDAP bind", e); throw new InvalidParameterValueException("Unable to bind to the given LDAP server"); } finally { closeContext(context); } } else { throw new InvalidParameterValueException("Duplicate configuration"); } }
Example #9
Source File: LdapTemplateRenameTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { // Setup ContextSource mock contextSourceMock = mock(ContextSource.class); // Setup LdapContext mock dirContextMock = mock(LdapContext.class); // Setup Name mock for old name oldNameMock = mock(Name.class); // Setup Name mock for new name newNameMock = mock(Name.class); tested = new LdapTemplate(contextSourceMock); }
Example #10
Source File: DelegatingLdapContext.java From spring-ldap with Apache License 2.0 | 6 votes |
/** * @see Object#equals(Object) */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof LdapContext)) { return false; } final LdapContext thisLdapContext = this.getInnermostDelegateLdapContext(); LdapContext otherLdapContext = (LdapContext)obj; if (otherLdapContext instanceof DelegatingLdapContext) { otherLdapContext = ((DelegatingLdapContext)otherLdapContext).getInnermostDelegateLdapContext(); } return thisLdapContext == otherLdapContext || (thisLdapContext != null && thisLdapContext.equals(otherLdapContext)); }
Example #11
Source File: LdapContextWrapper.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * Initialize the LDAP context with secured connection by applying StartTLS extended operation. * * @param environment environment used to create the initial Context. * @param connectionControls connection request controls for the initial context. * @return secured ldap connection context. * @throws NamingException if a naming exception is encountered. * @throws UserStoreException if a user store related exception is encountered. */ public static LdapContext startTLS(Hashtable<?, ?> environment, Control[] connectionControls) throws NamingException, UserStoreException { Hashtable<String, Object> tempEnv = getEnvironmentForSecuredLdapInitialization(environment); LdapContext ldapContext = new InitialLdapContext(tempEnv, connectionControls); try { StartTlsResponse startTlsResponse = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest()); startTlsResponse.negotiate(); if (log.isDebugEnabled()) { log.debug("StartTLS connection established successfully with LDAP server"); } LdapContextWrapper ldapContextWrapper = new LdapContextWrapper(ldapContext, startTlsResponse); ldapContextWrapper.performAuthenticationIfProvided(environment); return ldapContextWrapper; } catch (IOException e) { throw new UserStoreException("Unable to establish the StartTLS connection", e); } }
Example #12
Source File: TriggerUtils.java From directory-ldap-api with Apache License 2.0 | 6 votes |
/** * Create the Trigger execution subentry * * @param apCtx The administration point context * @param subentryCN The CN used by the suentry * @param subtreeSpec The subtree specification * @param prescriptiveTriggerSpec The prescriptive trigger specification * @throws NamingException If the operation failed */ public static void createTriggerExecutionSubentry( LdapContext apCtx, String subentryCN, String subtreeSpec, String prescriptiveTriggerSpec ) throws NamingException { Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true ); Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT ); subentry.put( objectClass ); objectClass.add( SchemaConstants.TOP_OC ); objectClass.add( SchemaConstants.SUBENTRY_OC ); objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC ); subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec ); subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec ); apCtx.createSubcontext( "cn=" + subentryCN, subentry ); }
Example #13
Source File: LDAPServerPolicyHintsDecorator.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void beforeLDAPOperation(LdapContext ldapContext, LDAPOperationManager.LdapOperation ldapOperation) throws NamingException { logger.debug("Applying LDAP_PASSWORD_POLICY_HINTS_OID before update password"); final byte[] controlData = {48, (byte) 132, 0, 0, 0, 3, 2, 1, 1}; // Rather using deprecated OID as it works from MSAD 2008-R2 when the newer works from MSAD 2012 BasicControl control = new BasicControl(LDAP_SERVER_POLICY_HINTS_DEPRECATED_OID, true, controlData); BasicControl[] controls = new BasicControl[] { control }; ldapContext.setRequestControls(controls); }
Example #14
Source File: TransactionAwareContextSourceProxyTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testGetReadWriteContext_LdapContext() { when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); DirContext result = tested.getReadWriteContext(); assertThat(result).isNotNull(); assertThat(result instanceof LdapContext).isTrue(); assertThat(result instanceof DirContextProxy).isTrue(); }
Example #15
Source File: RetryingLdapContext.java From james-project with Apache License 2.0 | 5 votes |
@Override public void setRequestControls(final Control[] requestControls) throws NamingException { new LoggingRetryHandler(DEFAULT_EXCEPTION_CLASSES, this, getSchedule(), getMaxRetries()) { @Override public Object operation() throws NamingException { ((LdapContext) getDelegate()).setRequestControls(requestControls); return null; } }.perform(); }
Example #16
Source File: OpenLdapUserManagerImpl.java From cosmic with Apache License 2.0 | 5 votes |
@Override public LdapUser getUser(final String username, final LdapContext context) throws NamingException, IOException { final List<LdapUser> result = searchUsers(username, context); if (result != null && result.size() == 1) { return result.get(0); } else { throw new NamingException("No user found for username " + username); } }
Example #17
Source File: LdapManagerImpl.java From cloudstack with Apache License 2.0 | 5 votes |
@Override public List<LdapUser> searchUsers(final String username) throws NoLdapUserMatchingQueryException { LdapContext context = null; try { // TODO search users per domain (only?) context = _ldapContextFactory.createBindContext(null); final String escapedUsername = LdapUtils.escapeLDAPSearchFilter(username); return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider(null)).getUsers("*" + escapedUsername + "*", context, null); } catch (NamingException | IOException e) { LOGGER.debug("ldap Exception: ",e); throw new NoLdapUserMatchingQueryException(username); } finally { closeContext(context); } }
Example #18
Source File: TransactionAwareContextSourceProxyTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testGetReadOnlyContext_LdapContext() { when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); DirContext result = tested.getReadOnlyContext(); assertThat(result).as("Result should not be null").isNotNull(); assertThat(result instanceof LdapContext).isTrue(); assertThat(result instanceof DirContextProxy).isTrue(); }
Example #19
Source File: TransactionAwareContextSourceProxyTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testGetReadWriteContext_DirContext() { when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); DirContext result = tested.getReadWriteContext(); assertThat(result).as("Result should not be null").isNotNull(); assertThat(result instanceof DirContext).isTrue(); assertThat(result instanceof LdapContext).isFalse(); assertThat(result instanceof DirContextProxy).isTrue(); }
Example #20
Source File: LdapManagerImpl.java From cosmic with Apache License 2.0 | 5 votes |
@Override public List<LdapUser> getUsers() throws NoLdapUserMatchingQueryException { LdapContext context = null; try { context = _ldapContextFactory.createBindContext(); return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider()).getUsers(context); } catch (NamingException | IOException e) { s_logger.debug("ldap Exception: ", e); throw new NoLdapUserMatchingQueryException("*"); } finally { closeContext(context); } }
Example #21
Source File: RetryingLdapContext.java From james-project with Apache License 2.0 | 5 votes |
@Override public Control[] getRequestControls() throws NamingException { return (Control[]) new LoggingRetryHandler(DEFAULT_EXCEPTION_CLASSES, this, getSchedule(), getMaxRetries()) { @Override public Object operation() throws NamingException { return ((LdapContext) getDelegate()).getRequestControls(); } }.perform(); }
Example #22
Source File: LdapManagerImpl.java From cloudstack with Apache License 2.0 | 5 votes |
@Override public List<LdapUser> getUsersInGroup(String groupName, Long domainId) throws NoLdapUserMatchingQueryException { LdapContext context = null; try { context = _ldapContextFactory.createBindContext(domainId); return _ldapUserManagerFactory.getInstance(_ldapConfiguration.getLdapProvider(domainId)).getUsersInGroup(groupName, context, domainId); } catch (NamingException | IOException e) { LOGGER.debug("ldap NamingException: ",e); throw new NoLdapUserMatchingQueryException("groupName=" + groupName); } finally { closeContext(context); } }
Example #23
Source File: DelegatingLdapContext.java From quarkus with Apache License 2.0 | 5 votes |
@Override public void reconnect(Control[] controls) throws NamingException { if (!(delegating instanceof LdapContext)) throw Assert.unsupported(); ClassLoader previous = setSocketFactory(); try { ((LdapContext) delegating).reconnect(controls); } finally { unsetSocketFactory(previous); } }
Example #24
Source File: JndiLdapRealmWithUser.java From jesterj with Apache License 2.0 | 5 votes |
@Override protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext) throws NamingException { SimpleAuthenticationInfo authenticationInfo = (SimpleAuthenticationInfo) super.createAuthenticationInfo(token, ldapPrincipal, ldapCredentials, ldapContext); MutablePrincipalCollection mpc = (MutablePrincipalCollection) authenticationInfo.getPrincipals(); final SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); // get all attributes constraints.setReturningAttributes(null); String templ = getUserDnTemplate(); String userDn = MessageFormat.format(templ, mpc.getPrimaryPrincipal()); final NamingEnumeration<SearchResult> answer = ldapContext.search(userDn, "(objectClass=*)", constraints); if (answer.hasMore()) { Attributes attrs = answer.next().getAttributes(); if (answer.hasMore()) { throw new NamingException("Non-unique user specified by:" + userDn); } //TODO: make this Guicy User user = new UserFromLdap(attrs, mpc); // at present there should only be one realm involved. Iterator<String> realmIter = mpc.getRealmNames().iterator(); String firstRealm = realmIter.next(); if (realmIter.hasNext()) { // ugh, need a new solution here String explanation = String.format("More than one realm found! (%s and %s)", firstRealm, realmIter.next()); throw new NamingException(explanation); } mpc.add(user,firstRealm); } else { throw new NamingException("Invalid User specified by:" + userDn); } return authenticationInfo; }
Example #25
Source File: OpenLdapUserManagerImpl.java From cosmic with Apache License 2.0 | 5 votes |
private LdapUser getUserForDn(final String userdn, final LdapContext context) throws NamingException { final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); final NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls); if (result.hasMoreElements()) { return createUser(result.nextElement()); } else { throw new NamingException("No user found for dn " + userdn); } }
Example #26
Source File: LdapIntegrationTest.java From wildfly-camel with Apache License 2.0 | 5 votes |
private LdapContext getWiredContext(int port) throws Exception { Hashtable<String, String> env = new Hashtable<String, String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" ); env.put( Context.PROVIDER_URL, Network.ldapLoopbackUrl( port ) ); env.put( Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN ); env.put( Context.SECURITY_CREDENTIALS, "secret" ); env.put( Context.SECURITY_AUTHENTICATION, "simple" ); LdapApiService ldapApiService = new StandaloneLdapApiService(); return new InitialLdapContext( env, JndiUtils.toJndiControls(ldapApiService, null ) ); }
Example #27
Source File: OpenLdapUserManagerImpl.java From cosmic with Apache License 2.0 | 5 votes |
@Override public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException { final String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute(); final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(new String[]{attributeName}); final NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls); final List<LdapUser> users = new ArrayList<>(); //Expecting only one result which has all the users if (result.hasMoreElements()) { final Attribute attribute = result.nextElement().getAttributes().get(attributeName); final NamingEnumeration<?> values = attribute.getAll(); while (values.hasMoreElements()) { final String userdn = String.valueOf(values.nextElement()); try { users.add(getUserForDn(userdn, context)); } catch (final NamingException e) { s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); } } } Collections.sort(users); return users; }
Example #28
Source File: LdapGroupRealm.java From zeppelin with Apache License 2.0 | 5 votes |
public AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException { String username = (String) getAvailablePrincipal(principals); LdapContext ldapContext = ldapContextFactory.getSystemLdapContext(); Set<String> roleNames = getRoleNamesForUser(username, ldapContext, getUserDnTemplate()); return new SimpleAuthorizationInfo(roleNames); }
Example #29
Source File: KnoxLdapRealm.java From knox with Apache License 2.0 | 5 votes |
@Override protected AuthenticationInfo createAuthenticationInfo( AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext) throws NamingException { return super.createAuthenticationInfo(token, ldapPrincipal, ldapCredentials, ldapContext); }
Example #30
Source File: LdapAuthenticationImpl.java From vertx-auth with Apache License 2.0 | 5 votes |
private void createLdapContext(String principal, String credential, Handler<AsyncResult<LdapContext>> resultHandler) { Hashtable<String, Object> environment = new Hashtable<>(); // set the initial cntext factory environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // set the url environment.put(Context.PROVIDER_URL, authenticationOptions.getUrl()); if (principal != null) { environment.put(Context.SECURITY_PRINCIPAL, principal); } if (credential != null) { environment.put(Context.SECURITY_CREDENTIALS, credential); } if (authenticationOptions.getAuthenticationMechanism() == null && (principal != null || credential != null)) { environment.put(Context.SECURITY_AUTHENTICATION, SIMPLE_AUTHENTICATION_MECHANISM); } // referral environment.put(Context.REFERRAL, authenticationOptions.getReferral() == null ? FOLLOW_REFERRAL : authenticationOptions.getReferral()); vertx.executeBlocking(blockingResult -> { try { LdapContext context = new InitialLdapContext(environment, null); blockingResult.complete(context); } catch (Throwable t) { blockingResult.fail(t); } }, resultHandler); }