类javax.naming.ldap.LdapContext源码实例Demo

下面列出了怎么用javax.naming.ldap.LdapContext的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: micro-integrator   文件: LdapContextWrapper.java
/**
 * 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);
    }
}
 
源代码2 项目: ranger   文件: LdapConfigCheckMain.java
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);
}
 
源代码3 项目: cloudstack   文件: LdapManagerImpl.java
@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);
    }
}
 
源代码4 项目: glowroot   文件: LdapAuthentication.java
@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();
    }
}
 
源代码5 项目: glowroot   文件: LdapAuthentication.java
@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();
    }
}
 
源代码6 项目: projectforge-webapp   文件: LdapConnector.java
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);
  }
}
 
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);
	}
 
源代码8 项目: spring-ldap   文件: DelegatingLdapContext.java
/**
 * @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));
}
 
源代码9 项目: directory-ldap-api   文件: TriggerUtils.java
/**
 * 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 );
}
 
源代码10 项目: cosmic   文件: LdapManagerImpl.java
@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");
    }
}
 
源代码11 项目: spring-ldap   文件: LdapTemplateRenameTest.java
@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);
}
 
源代码12 项目: olat   文件: LDAPLoginManagerImpl.java
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;
}
 
源代码13 项目: olat   文件: LDAPLoginITCase.java
@Test
public void testSystemBind() {
    if (!LDAPLoginModule.isLDAPEnabled()) {
        return;
    }

    // edit olatextconfig.xml for testing
    final LDAPLoginManager ldapManager = (LDAPLoginManager) CoreSpringFactory.getBean(LDAPLoginManager.class);
    final LdapContext ctx = ldapManager.bindSystem();
    assertEquals(true, (ctx != null));
}
 
源代码14 项目: micro-integrator   文件: LDAPConnectionContext.java
/**
 * Initialize the LDAP context.
 *
 * @param environment        environment used to create the initial Context.
 * @param connectionControls connection request controls for the initial context.
 * @return ldap connection context.
 * @throws NamingException    if a naming exception is encountered.
 * @throws UserStoreException if a user store related exception is encountered.
 */
private LdapContext initializeLdapContext(Hashtable<?, ?> environment, Control[] connectionControls)
        throws NamingException, UserStoreException {

    if (startTLSEnabled) {
        return LdapContextWrapper.startTLS(environment, connectionControls);
    } else {
        return new InitialLdapContext(environment, connectionControls);
    }
}
 
源代码15 项目: micro-integrator   文件: LdapContextWrapper.java
private LdapContextWrapper(LdapContext ldapContext, StartTlsResponse startTlsResponse) {

        this.ldapContext = ldapContext;
        this.startTlsResponse = startTlsResponse;
        this.startTlsResponseWrapper = new StartTlsResponseWrapper(this.startTlsResponse);
        this.startTlsResponseWrapper.incrementReferenceCounter();
    }
 
源代码16 项目: james-project   文件: RetryingLdapContext.java
@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();
}
 
源代码17 项目: spring-ldap   文件: DelegatingLdapContext.java
/**
 * Recursivley inspect delegates until a non-delegating ldap context is found.
 *
 * @return The innermost (real) DirContext that is being delegated to.
 */
public LdapContext getInnermostDelegateLdapContext() {
    final LdapContext delegateLdapContext = this.getDelegateLdapContext();

    if (delegateLdapContext instanceof DelegatingLdapContext) {
        return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext();
    }

    return delegateLdapContext;
}
 
源代码18 项目: micro-integrator   文件: CarbonContextDataHolder.java
private LdapContext getLdapContext() throws NamingException {
    DirContext dirContext = getDirectoryContext();
    if (dirContext instanceof EventContext) {
        return (LdapContext) dirContext;
    }
    throw new NamingException("The given Context is not an instance of "
                              + LdapContext.class.getName());
}
 
源代码19 项目: ranger   文件: UserSync.java
public void findUserProperties(LdapContext ldapContext) throws Throwable {
    // 1. find basic user properties
    // 2. find user search base and user search filter by passing basic attributes

    findBasicUserProperties(ldapContext, true);

    findAdvUserProperties(ldapContext, true);
}
 
源代码20 项目: zeppelin   文件: LdapRealm.java
@Override
protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token,
    Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext)
    throws NamingException {
  HashRequest.Builder builder = new HashRequest.Builder();
  Hash credentialsHash = hashService
      .computeHash(builder.setSource(token.getCredentials())
          .setAlgorithmName(HASHING_ALGORITHM).build());
  return new SimpleAuthenticationInfo(token.getPrincipal(),
      credentialsHash.toHex(), credentialsHash.getSalt(),
      getName());
}
 
源代码21 项目: ldapchai   文件: JNDIProviderImpl.java
@LdapOperation
@ModifyOperation
public final void replaceStringAttribute( final String entryDN, final String attributeName, final String oldValue, final String newValue )
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().replaceStringAttribute( entryDN, attributeName, oldValue, newValue );

    // Create the ModificationItem
    final ModificationItem[] mods = new ModificationItem[2];

    // Mark the flag to remover the existing attribute.
    mods[0] = new ModificationItem( DirContext.REMOVE_ATTRIBUTE, new BasicAttribute( attributeName, oldValue ) );

    // Mark the flag to add the new attribute
    mods[1] = new ModificationItem( DirContext.ADD_ATTRIBUTE, new BasicAttribute( attributeName, newValue ) );

    // get ldap connection
    final LdapContext ldapConnection = getLdapConnection();

    // Modify the Attributes.
    try
    {
        ldapConnection.modifyAttributes( addJndiEscape( entryDN ), mods );
    }
    catch ( NamingException e )
    {
        convertNamingException( e );
    }
}
 
源代码22 项目: cloudstack   文件: LdapManagerImpl.java
@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);
    }
}
 
源代码23 项目: cloudstack   文件: LdapManagerImpl.java
@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);
    }
}
 
源代码24 项目: quarkus   文件: DelegatingLdapContext.java
@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);
    }
}
 
源代码25 项目: cosmic   文件: OpenLdapUserManagerImpl.java
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);
    }
}
 
源代码26 项目: wildfly-camel   文件: LdapIntegrationTest.java
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 ) );
}
 
源代码27 项目: knox   文件: KnoxLdapRealm.java
@Override
protected AuthenticationInfo createAuthenticationInfo(
    AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials,
    LdapContext ldapContext) throws NamingException {
  return super.createAuthenticationInfo(token, ldapPrincipal, ldapCredentials,
      ldapContext);
}
 
源代码28 项目: vertx-auth   文件: LdapAuthenticationImpl.java
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);
}
 
源代码29 项目: zeppelin   文件: LdapGroupRealm.java
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);
}
 
源代码30 项目: cosmic   文件: OpenLdapUserManagerImpl.java
@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;
}
 
 类所在包
 同包方法