javax.naming.ldap.InitialLdapContext Java Examples

The following examples show how to use javax.naming.ldap.InitialLdapContext. 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: LdapContextWrapper.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
private DirContext buildSearchContext(String username, String password) {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapConfiguration.getUrl());
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());
    env.put("com.sun.jndi.ldap.connect.timeout", ldapConfiguration.getConnectTimeout());
    env.put("com.sun.jndi.ldap.read.timeout", ldapConfiguration.getReadTimeout());
    env.put(Context.SECURITY_PRINCIPAL, String.format("%s\\%s", ldapConfiguration.getDomain(), username));
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext dirContext = new InitialLdapContext(env, null);
        // ici dirContext ne contient que des infos relatives au serveur avec lequel la connexion vient d'être établie
        if (log.isDebugEnabled()) { // on évite ce traitement si ce n'est pas nécessaire
            log.debug("[buildSearchContext] dirContext: {}", gson.toJson(attributesToNative(dirContext.getAttributes("").getAll())));
        }
        return dirContext;
    } catch (AuthenticationException | OperationNotSupportedException cause) {
        throw new BadCredentialsException(messages.getMessage(
                "LdapAuthenticationProvider.badCredentials", "Bad credentials"), cause);
    } catch (NamingException e) {
        log.error(e.getExplanation() + (e.getCause() != null ? (" : " + e.getCause().getMessage()) : ""));
        throw LdapUtils.convertLdapException(e);
    }
}
 
Example #3
Source File: ApacheKDCServer.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void setSchemaContext(KdcConfiguration configuration, DirectoryService service,
                              String connectionUser)
        throws DirectoryServerException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, service);
    env.put(Context.SECURITY_PRINCIPAL, connectionUser);
    env.put(Context.SECURITY_CREDENTIALS, configuration.getSystemAdminPassword());
    env.put(Context.SECURITY_AUTHENTICATION, ConfigurationConstants.SIMPLE_AUTHENTICATION);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());

    env.put(Context.PROVIDER_URL, SchemaConstants.OU_SCHEMA);

    try {
        schemaRoot = new InitialLdapContext(env, null);
    } catch (NamingException e) {
        throw new DirectoryServerException(
                "Unable to create Schema context with user " + connectionUser, e);
    }

}
 
Example #4
Source File: LDAPAuthenticationService.java    From proxylive with MIT License 6 votes vote down vote up
@PostConstruct
private void initialize() throws MalformedURLException, ProtocolException, IOException, ParseException, NamingException {
    ldapAuthConfig = configuration.getAuthentication().getLdap();
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapAuthConfig.getUser());
    env.put(Context.SECURITY_CREDENTIALS, ldapAuthConfig.getPassword());
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://"+ldapAuthConfig.getServer()+"/"+ldapAuthConfig.getSearchBase());
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    LdapContext ctx = new InitialLdapContext();
    SearchResult srLdapUser = findAccountByAccountName(ctx, ldapAuthConfig.getSearchBase(), "segator");
       String primaryGroupSID = getPrimaryGroupSID(srLdapUser);
 
    
    //3) get the users Primary Group
    String primaryGroupName = findGroupBySID(ctx, ldapAuthConfig.getSearchBase(), primaryGroupSID);
    logger.trace(primaryGroupName);

}
 
Example #5
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testLdapDnAuthentication() throws NamingException {
    String dn = new Rdn("uid", Settings.getProperty("davmail.username"))+",ou=people";
    Hashtable<String, String> env = new Hashtable<>();
    //env.put("java.naming.security.authentication", "CRAM-MD5");
    env.put("java.naming.security.authentication", "simple");
    env.put("java.naming.security.principal", dn);
    env.put("java.naming.security.credentials", Settings.getProperty("davmail.password"));

    env.put("com.sun.jndi.ldap.connect.pool", "true");
    env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    env.put("java.naming.provider.url", "ldap://127.0.0.1:" + Settings.getIntProperty("davmail.ldapPort"));
    env.put("java.naming.referral", "follow");

    new InitialLdapContext(env, null);

}
 
Example #6
Source File: LdapConnector.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: LdapSimpleAuthenticator.java    From juddi with Apache License 2.0 5 votes vote down vote up
public void init(String url) throws NamingException, ConfigurationException {
    env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
    env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));
    env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389

    this.url = url;
    
    try {
        ctx = new InitialLdapContext(env, null);
    } catch (NamingException e) {
        logger.error("Naming exception " + e);
        throw e;
    }
}
 
Example #8
Source File: LdapCallbackHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
	Properties env = new Properties();
	for (Entry<String, String> entry : options.entrySet())
	{
		env.put(entry.getKey(), entry.getValue());
	}

	// Set defaults for key values if they are missing
	String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
	if (factoryName == null)
	{
		factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
		env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
	}
	String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
	if (authType == null)
		env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
	String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
	String providerURL = options.get(Context.PROVIDER_URL);
	if (providerURL == null)
		providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");

	env.setProperty(Context.PROVIDER_URL, providerURL);

	distinguishedNameAttribute = options.get(DISTINGUISHED_NAME_ATTRIBUTE_OPT);
      if (distinguishedNameAttribute == null)
          distinguishedNameAttribute = "distinguishedName";


	// JBAS-3555, allow anonymous login with no bindDN and bindCredential
	if (dn != null)
		env.setProperty(Context.SECURITY_PRINCIPAL, dn);
	if (credential != null)
		env.put(Context.SECURITY_CREDENTIALS, credential);
       this.traceLDAPEnv(env);
       return new InitialLdapContext(env, null);
}
 
Example #9
Source File: LdapCallbackHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void safeClose(InitialLdapContext ic)
{
	if(ic != null)
	{
		try
		{
			ic.close();
		}
		catch (NamingException e)
		{
		}
	}
}
 
Example #10
Source File: LdapMockProtocol.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public InitialLdapContext getCtx() {
  if ( mockContext == null ) {
    throw new RuntimeException( "LDAP Mock Connection was not setup" );
  } else {
    return mockContext;
  }
}
 
Example #11
Source File: ReadOnlyLDAPUsersDAO.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Answers a new LDAP/JNDI context using the specified user credentials.
 *
 * @return an LDAP directory context
 * @throws NamingException
 *             Propagated from underlying LDAP communication API.
 */
protected LdapContext computeLdapContext() throws NamingException {
    return new RetryingLdapContext(schedule, ldapConfiguration.getMaxRetries()) {

        @Override
        public Context newDelegate() throws NamingException {
            return new InitialLdapContext(getContextEnvironment(), null);
        }
    };
}
 
Example #12
Source File: LDAPConnectionContext.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #13
Source File: LdapUserGroupBuilder.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void createLdapContext() throws Throwable {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY,
			"com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, ldapUrl);
	if (ldapUrl.startsWith("ldaps") && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) {
		env.put("java.naming.ldap.factory.socket", "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory");
	}

	ldapContext = new InitialLdapContext(env, null);
	if (!ldapUrl.startsWith("ldaps")) {
		if (config.isStartTlsEnabled()) {
			tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
			if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) {
				tls.negotiate(CustomSSLSocketFactory.getDefault());
			} else {
				tls.negotiate();
			}
			LOG.info("Starting TLS session...");
		}
	}

	ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn);
	ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword);
	ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
	ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral);
}
 
Example #14
Source File: LdapAuthenticate.java    From Hue-Ctrip-DI with MIT License 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public LdapContext connectLdap(String ldapAccount, String ldapPwd,
		String range) throws NamingException {
	String ldapFactory = "com.sun.jndi.ldap.LdapCtxFactory";
	Hashtable env = new Hashtable();
	env.put(Context.INITIAL_CONTEXT_FACTORY, ldapFactory);
	env.put(Context.PROVIDER_URL, ldapUrl);
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, range + "\\" + ldapAccount);
	env.put(Context.SECURITY_CREDENTIALS, ldapPwd);
	env.put("java.naming.referral", "follow");
	LdapContext ctxTDS = new InitialLdapContext(env, null);
	return ctxTDS;
}
 
Example #15
Source File: LdapManager.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @return a newly created DirContext.
 */
public void openContext() throws NamingException {
	/* DEBUG : verify parameters passed to the context */
	/*
	 System.out.println("*** environnement properties ***");
	 for (Enumeration e = env.keys() ; e.hasMoreElements() ;) {
	 String key = e.nextElement().toString();
	 String value = env.get(key).toString();
	 if (value.length() > 80) {
	 value = value.substring(0, 77) + "...";
	 }
	 System.out.println(key + "=" + value);
	 }
	 System.out.println("*****************");
	 */
	
	if (ldapContext){
		this.ctx = new InitialLdapContext(this.env,null);
	}else{
		this.ctx = new InitialDirContext(this.env);
	}

	if (ctx == null)
		throw new NamingException(
				"Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");

}
 
Example #16
Source File: LdapConnector.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public LdapContext createContext(final String username, final String password) throws NamingException
{
  init();
  final Hashtable<String, String> env = createEnv(username, password);
  final LdapContext ctx = new InitialLdapContext(env, null);
  return ctx;
}
 
Example #17
Source File: LdapTlsProtocolIT.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws NamingException {
  mockLogChannelInterface = mock( LogChannelInterface.class );
  mockVariableSpace = mock( VariableSpace.class );
  mockLdapMeta = mock( LdapMeta.class );
  mockInitialLdapContext = mock( InitialLdapContext.class );
  mockStartTlsResponse = mock( StartTlsResponse.class );
  when( mockInitialLdapContext.extendedOperation( any( StartTlsRequest.class ) ) ).thenReturn(
    mockStartTlsResponse );
}
 
Example #18
Source File: LdapExpandedAuthenticator.java    From juddi with Apache License 2.0 5 votes vote down vote up
public void init(String url) throws NamingException, ConfigurationException {
    env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
    env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));
    env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389

    this.url = url;
    
    try {
        ctx = new InitialLdapContext(env, null);
    } catch (NamingException e) {
        logger.error("Naming exception " + e);
        throw e;
    }
}
 
Example #19
Source File: LDAPContextManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void createLdapContext() throws NamingException {
    Hashtable<Object, Object> connProp = getConnectionProperties(ldapConfig);

    if (!LDAPConstants.AUTH_TYPE_NONE.equals(ldapConfig.getAuthType())) {
        vaultCharSecret = getVaultSecret();

        if (vaultCharSecret != null && !ldapConfig.isStartTls()) {
            connProp.put(SECURITY_CREDENTIALS, vaultCharSecret.getAsArray()
                    .orElse(ldapConfig.getBindCredential().toCharArray()));
        }
    }

    ldapContext = new InitialLdapContext(connProp, null);
    if (ldapConfig.isStartTls()) {
        SSLSocketFactory sslSocketFactory = null;
        String useTruststoreSpi = ldapConfig.getUseTruststoreSpi();
        if (useTruststoreSpi != null && useTruststoreSpi.equals(LDAPConstants.USE_TRUSTSTORE_ALWAYS)) {
            TruststoreProvider provider = session.getProvider(TruststoreProvider.class);
            sslSocketFactory = provider.getSSLSocketFactory();
        }

        tlsResponse = startTLS(ldapContext, ldapConfig.getAuthType(), ldapConfig.getBindDN(),
                vaultCharSecret.getAsArray().orElse(ldapConfig.getBindCredential().toCharArray()), sslSocketFactory);

        // Exception should be already thrown by LDAPContextManager.startTLS if "startTLS" could not be established, but rather do some additional check
        if (tlsResponse == null) {
            throw new NamingException("Wasn't able to establish LDAP connection through StartTLS");
        }
    }
}
 
Example #20
Source File: LdapAuthentication.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Instrumentation.TraceEntry(message = "create ldap context", timer = "ldap")
private static LdapContext createLdapContext(String username, String password,
        LdapConfig ldapConfig) throws NamingException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapConfig.url());
    return new InitialLdapContext(env, null);
}
 
Example #21
Source File: LdapSearch.java    From cxf with Apache License 2.0 5 votes vote down vote up
private InitialDirContext createInitialContext() throws NamingException {
    Hashtable<String, String> env = new Hashtable<>(5); //NOPMD
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, ldapuri);
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, bindDN);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, bindPassword);
    return new InitialLdapContext(env, null);
}
 
Example #22
Source File: LdapAuthenticationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source File: LdapIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: LdapExtLoginModule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
    String protocol = (String)options.get(Context.SECURITY_PROTOCOL);
    String providerURL = (String) options.get(Context.PROVIDER_URL);
    if (providerURL == null)
       providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");

    Properties env = constructLdapContextEnvironment(providerURL, dn, credential);
    return new InitialLdapContext(env, null);
}
 
Example #25
Source File: LdapUserService.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void doInitUser(Map<String, UserInfo> userInfos, Map<String, Organization> orgMap, String serverPath)
		throws NamingException {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_PRINCIPAL, "corp\\" + soaConfig.getMqLdapUser());
	env.put(Context.SECURITY_CREDENTIALS, soaConfig.getMqLdapPass());
	env.put(Context.PROVIDER_URL, adServer.get());

	LdapContext ctx = new InitialLdapContext(env, null);
	SearchControls searchCtls = new SearchControls();
	searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

	String searchFilter = String
			.format("(&(objectClass=top)(objectClass=user)(objectClass=person)(objectClass=organizationalPerson))");

	String returnedAtts[] = { "memberOf", "sAMAccountName", "cn", "distinguishedName", "mail" };
	searchCtls.setReturningAttributes(returnedAtts);
	NamingEnumeration<SearchResult> answer = ctx.search(serverPath, searchFilter, searchCtls);
	while (answer.hasMoreElements()) {
		SearchResult sr = (SearchResult) answer.next();
		Attributes at = sr.getAttributes();
		UserInfo userInfo = new UserInfo();
		userInfo.setDepartment(getDValue(at.get("distinguishedName")));
		userInfo.setEmail(getValue(at.get("mail")));
		userInfo.setUserId(getValue(at.get("sAMAccountName")));
		userInfo.setName(getValue(at.get("cn")));
		userInfo.setAdmin(roleService.isAdmin(userInfo.getUserId()));
		userInfos.put(userInfo.getUserId(), userInfo);
		if (!StringUtils.isEmpty(userInfo.getDepartment())) {
			Organization organization = new Organization();
			organization.setOrgId(userInfo.getDepartment());
			orgMap.put(userInfo.getDepartment(), organization);
		}
	}
	ctx.close();
}
 
Example #26
Source File: LdapMockProtocol.java    From hop with Apache License 2.0 5 votes vote down vote up
@Override
public InitialLdapContext getCtx() {
  if ( mockContext == null ) {
    throw new RuntimeException( "LDAP Mock Connection was not setup" );
  } else {
    return mockContext;
  }
}
 
Example #27
Source File: LdapMockProtocol.java    From hop with Apache License 2.0 5 votes vote down vote up
@Override
public InitialLdapContext getCtx() {
  if ( mockContext == null ) {
    throw new RuntimeException( "LDAP Mock Connection was not setup" );
  } else {
    return mockContext;
  }
}
 
Example #28
Source File: DelegatingLdapContext.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public LdapContext newInitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException {
    ClassLoader previous = setSocketFactory();
    try {
        return new InitialLdapContext(environment, null);
    } finally {
        unsetSocketFactory(previous);
    }
}
 
Example #29
Source File: LoginServiceLdapImpl.java    From griffin with Apache License 2.0 5 votes vote down vote up
private LdapContext getContextInstance(String principal, String password)
    throws NamingException {
    Hashtable<String, String> ht = new Hashtable<>();
    ht.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_FACTORY);
    ht.put(Context.PROVIDER_URL, url);
    ht.put(Context.SECURITY_PRINCIPAL, principal);
    ht.put(Context.SECURITY_CREDENTIALS, password);
    if (url.startsWith("ldaps") && sslSkipVerify) {
        ht.put("java.naming.ldap.factory.socket", SelfSignedSocketFactory.class.getName());
    }
    return new InitialLdapContext(ht, null);
}
 
Example #30
Source File: LdapRolesMappingProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
   Properties env = new Properties();
   Iterator<Entry<String, Object>> iter = options.entrySet().iterator();
   while (iter.hasNext())
   {
      Entry<String, Object> entry = iter.next();
      env.put(entry.getKey(), entry.getValue());
   }

   // Set defaults for key values if they are missing
   String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
   if (factoryName == null)
   {
      factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
      env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
   }
   String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
   if (authType == null)
      env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
   String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
   String providerURL = (String) options.get(Context.PROVIDER_URL);
   if (providerURL == null)
      providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");

   env.setProperty(Context.PROVIDER_URL, providerURL);
   // JBAS-3555, allow anonymous login with no bindDN and bindCredential
   if (dn != null)
      env.setProperty(Context.SECURITY_PRINCIPAL, dn);
   if (credential != null)
      env.put(Context.SECURITY_CREDENTIALS, credential);
   this.traceLDAPEnv(env);
   return new InitialLdapContext(env, null);
}