Java 类javax.naming.ldap.InitialLdapContext 实例源码

项目:helium    文件:PersonesPluginLdap.java   
private LdapContext getContext() throws Exception {
    Hashtable<String, String> envDC = new Hashtable<String, String>();
    envDC.put(
            Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(
            Context.PROVIDER_URL,
            GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.url"));
    envDC.put(
            Context.SECURITY_AUTHENTICATION,
            "simple");
    envDC.put(
            Context.SECURITY_PRINCIPAL,
            GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.principal"));
    envDC.put(
            Context.SECURITY_CREDENTIALS,
            GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.credentials"));
    return new InitialLdapContext(envDC, null);
}
项目:SpineTools-Java    文件:SDSconnection.java   
private void init()
        throws Exception 
{
    @SuppressWarnings("UseOfObsoleteCollectionType")
    Hashtable<String,String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, sdsUrl);
    if (ConditionalCompilationControls.LDAPS && !ConditionalCompilationControls.OPENTEST) {
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put(Context.SECURITY_AUTHENTICATION, "none");
        if (ConditionalCompilationControls.LDAPOVERTLS && !ConditionalCompilationControls.OPENTEST) {
            env.put("java.naming.ldap.factory.socket", "org.warlock.spine.connection.SpineSecurityContext");
        }
    }
    ldapContext = new InitialLdapContext(env, null);
}
项目:carbon-identity    文件:ApacheKDCServer.java   
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);
    }

}
项目:picketbox    文件:LdapExtLoginModule.java   
/**
 * This method validates absoluteName and credential against referral LDAP and returns used user DN.
 *
 * <ol>
 * <li> Parses given absoluteName to URL and DN
 * <li> creates initial LDAP context of referral LDAP to validate credential
 * <li> closes the initial context
 * </ol>
 *
 * It uses all options from login module setup except of ProviderURL.
 *
 * @param userDN - userDN which has to be used instead of parsed absoluteName (if is null, use absoluteName) - value is gained using distinguishedNameAttribute
 * @param absoluteName - absolute user DN
 * @param credential
 * @return used user DN for validation
 * @throws NamingException
 */
private String bindDNReferralAuthentication(final String userDN, String absoluteName, Object credential)
        throws NamingException
{
    URI uri;
    try {
        uri = new URI(absoluteName);
    }
    catch (URISyntaxException e)
    {
        throw PicketBoxMessages.MESSAGES.unableToParseReferralAbsoluteName(e, absoluteName);
    }
    String name = (userDN != null ? userDN : uri.getPath().substring(1));
    String namingProviderURL = uri.getScheme() + "://" + uri.getAuthority();

    Properties refEnv = constructLdapContextEnvironment(namingProviderURL, name, credential);

    InitialLdapContext refCtx = new InitialLdapContext(refEnv, null);
    refCtx.close();
 return name;
}
项目:cn1    文件:TestControlFactoryWhiteBoxDevelopment.java   
/**
 * <p>Test method for 'javax.naming.ldap.ControlFactory.getControlInstance(Control)'</p>
 * <p>Here we are going to test if we can get an instance with the controls sended.</p>
 */
public void testGetControlInstanceControl() {

    try {

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
        MockControl[] cs = { new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }), 
                new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
        MockControl cs2 =  new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }); 
        InitialLdapContext ilc=new InitialLdapContext(env, cs);
        assertEquals(cs2,ControlFactory.getControlInstance(cs2,ilc,env));

    } catch (NamingException e) {

    }
}
项目:cn1    文件:TestInitialLdapContext.java   
/**
 * <p>
 * Test method for
 * 'javax.naming.ldap.InitialLdapContext.reconnect(Control[])'
 * </p>
 * <p>
 * Here we are testing if this method correctly reconnects to the LDAP
 * server. In this case we are using a different set of controls for the
 * reconnection.
 * </p>
 * <p>
 * The expected result is a reconection with the new set of controls.
 * </p>
 */
public void testReconnect003() throws Exception {
    System
            .setProperty(Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
    Control[] cs = {
            new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
            new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
    Control[] cs2 = {
            new MockControl("c2", false, new byte[] { 1, 2, 3, 4 }),
            new MockControl("c2", true, new byte[] { 'a', 'b', 'c', 'd' }), };
    InitialLdapContext ilc = new InitialLdapContext(null, cs);
    ilc.reconnect(cs2);
    assertEquals(cs2, ilc.getConnectControls());
    ilc.close();
}
项目:cn1    文件:LdapContextServerMockedTest.java   
public void testConnectControls3() throws Exception {
    // set connect controls by InitialLdapContext
    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });
    InitialLdapContext initialDirContext = new InitialLdapContext(env,
            new Control[] { new SortControl("", Control.NONCRITICAL) });

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_SEARCH_RESULT_DONE,
            new EncodableLdapResult(), null) });
    LdapContext context = (LdapContext) initialDirContext.lookup("");

    Control[] controls = context.getConnectControls();
    assertNotNull(controls);
    assertEquals(1, controls.length);
    Control c = controls[0];
    assertTrue(c instanceof SortControl);
    assertEquals(Control.NONCRITICAL, c.isCritical());

}
项目:lens    文件:LDAPBackedDatabaseUserConfigLoader.java   
/**
 * Find account by account name.
 *
 * @param accountName the account name
 * @return the search result
 * @throws NamingException the naming exception
 */
protected SearchResult findAccountByAccountName(String accountName) throws NamingException {
  String searchFilter = String.format(searchFilterPattern, accountName);
  SearchControls searchControls = new SearchControls();
  searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
  InitialLdapContext ctx = new InitialLdapContext(env, null);
  try {
    NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls);
    if (!results.hasMoreElements()) {
      throw new UserConfigLoaderException("LDAP Search returned no accounts");
    }
    SearchResult searchResult = results.nextElement();
    if (results.hasMoreElements()) {
      throw new UserConfigLoaderException("More than one account found in ldap search");
    }
    return searchResult;
  } finally {
    ctx.close();
  }
}
项目:freeVM    文件:TestControlFactoryWhiteBoxDevelopment.java   
/**
 * <p>Test method for 'javax.naming.ldap.ControlFactory.getControlInstance(Control)'</p>
 * <p>Here we are gonna test if we can get an instance with the controls sended.</p>
 */
public void testGetControlInstanceControl() {

    try {

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
        MockControl[] cs = { new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }), 
                new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
        MockControl cs2 =  new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }); 
        InitialLdapContext ilc=new InitialLdapContext(env, cs);
        assertEquals(cs2,ControlFactory.getControlInstance(cs2,ilc,env));

    } catch (NamingException e) {

    }
}
项目:freeVM    文件:TestInitialLdapContext.java   
/**
 * <p>
 * Test method for
 * 'javax.naming.ldap.InitialLdapContext.reconnect(Control[])'
 * </p>
 * <p>
 * Here we are testing if this method reconnects to the LDAP server using
 * the supplied controls and this context's environment. In this case we are
 * sending a new set of controls to reconection.
 * </p>
 * <p>
 * The expected result is a reconection with the new set of controls.
 * </p>
 */
public void testReconnect003() throws Exception {
    System
            .setProperty(Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
    Control[] cs = {
            new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
            new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
    Control[] cs2 = {
            new MockControl("c2", false, new byte[] { 1, 2, 3, 4 }),
            new MockControl("c2", true, new byte[] { 'a', 'b', 'c', 'd' }), };
    InitialLdapContext ilc = new InitialLdapContext(null, cs);
    ilc.reconnect(cs2);
    assertEquals(cs2, ilc.getConnectControls());
    ilc.close();
}
项目:freeVM    文件:TestControlFactoryWhiteBoxDevelopment.java   
/**
 * <p>Test method for 'javax.naming.ldap.ControlFactory.getControlInstance(Control)'</p>
 * <p>Here we are going to test if we can get an instance with the controls sended.</p>
 */
public void testGetControlInstanceControl() {

    try {

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
        MockControl[] cs = { new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }), 
                new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
        MockControl cs2 =  new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }); 
        InitialLdapContext ilc=new InitialLdapContext(env, cs);
        assertEquals(cs2,ControlFactory.getControlInstance(cs2,ilc,env));

    } catch (NamingException e) {

    }
}
项目:freeVM    文件:TestInitialLdapContext.java   
/**
 * <p>
 * Test method for
 * 'javax.naming.ldap.InitialLdapContext.reconnect(Control[])'
 * </p>
 * <p>
 * Here we are testing if this method correctly reconnects to the LDAP
 * server. In this case we are using a different set of controls for the
 * reconnection.
 * </p>
 * <p>
 * The expected result is a reconection with the new set of controls.
 * </p>
 */
public void testReconnect003() throws Exception {
    System
            .setProperty(Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
    Control[] cs = {
            new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
            new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
    Control[] cs2 = {
            new MockControl("c2", false, new byte[] { 1, 2, 3, 4 }),
            new MockControl("c2", true, new byte[] { 'a', 'b', 'c', 'd' }), };
    InitialLdapContext ilc = new InitialLdapContext(null, cs);
    ilc.reconnect(cs2);
    assertEquals(cs2, ilc.getConnectControls());
    ilc.close();
}
项目:freeVM    文件:LdapContextServerMockedTest.java   
public void testConnectControls3() throws Exception {
    // set connect controls by InitialLdapContext
    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });
    InitialLdapContext initialDirContext = new InitialLdapContext(env,
            new Control[] { new SortControl("", Control.NONCRITICAL) });

    server.setResponseSeq(new LdapMessage[] { new LdapMessage(
            LdapASN1Constant.OP_SEARCH_RESULT_DONE,
            new EncodableLdapResult(), null) });
    LdapContext context = (LdapContext) initialDirContext.lookup("");

    Control[] controls = context.getConnectControls();
    assertNotNull(controls);
    assertEquals(1, controls.length);
    Control c = controls[0];
    assertTrue(c instanceof SortControl);
    assertEquals(Control.NONCRITICAL, c.isCritical());

}
项目:freeVM    文件:Support_LdapTest.java   
protected void setUp() throws Exception {
    super.setUp();
    configuration = new MutableServerStartupConfiguration();
    configuration.setWorkingDirectory(new File(workingDir));
    cleanWorkingDir(configuration.getWorkingDirectory());
    port = AvailablePortFinder.getNextAvailable(1024);
    configuration.setLdapPort(port);
    // configuration.setShutdownHookEnabled(false);
    serverEnv = new Hashtable<String, Object>(configuration
            .toJndiEnvironment());

    initialAuth();

    serverEnv.put(Context.INITIAL_CONTEXT_FACTORY,
            ServerContextFactory.class.getName());

    serverEnv.put(Context.PROVIDER_URL, "");
    rootDSE = new InitialLdapContext(serverEnv, null);

}
项目:ndex-rest    文件:LDAPAuthenticator.java   
protected String getFullyQualifiedNameByUserId(String userId) throws UnauthorizedOperationException {

      env.put(Context.SECURITY_PRINCIPAL, ctxPrinciplePattern.replaceAll(userNamePattern, delegatedUserName));  
      env.put(Context.SECURITY_CREDENTIALS, delegatedUserPassword);
      try {
          LdapContext ctx = new InitialLdapContext(env,null);

          String searchFilter = searchFilterPattern.replaceAll(userNamePattern, userId);

          SearchControls searchControls = new SearchControls();
          searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
          NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase,
                  searchFilter, searchControls);

          SearchResult searchResult = null;
          if (results.hasMoreElements()) {
              searchResult = results.nextElement();
              return searchResult.getNameInNamespace();
          }
          return null;
      } catch (NamingException e) {
          throw new UnauthorizedOperationException(e.getMessage());
      }
}
项目: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);
  }
}
项目:opensearchserver    文件:ActiveDirectory.java   
public ActiveDirectory(String serverName, String username, String password,
        String domain) throws NamingException {
    if (StringUtils.isEmpty(domain))
        throw new NamingException("The domain is empty");
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");

    domainSearchName = getDomainSearch(domain);
    String login = StringUtils.fastConcat(username, "@", domain);
    if (serverName != null) {
        properties.put(Context.PROVIDER_URL,
                StringUtils.fastConcat("ldap://", serverName, ":389"));
    }
    properties.put(Context.SECURITY_PRINCIPAL, login);
    properties.put(Context.SECURITY_CREDENTIALS, password);
    properties.put(Context.REFERRAL, "follow");
    properties.put("java.naming.ldap.attributes.binary", "objectSID");
    dirContext = new InitialLdapContext(properties, null);
}
项目:some-ldap    文件:AbstractThreadLocalSessionFactory.java   
/**
 * Return the session which the current thread holds. If not exist, a new
 * session will be created and bind to current thread.
 * 
 * @return
 */
@Override
public Session getCurrentSession() {
    Map.Entry<Session, InitialLdapContext> current = sessions.get();
    if (null == current) {
        try {
            InitialLdapContext ldapConnection = getContext();
            Session session = new SessionImpl(this, ldapConnection, true);
            current = new AbstractMap.SimpleEntry<Session, InitialLdapContext>(
                    session, ldapConnection);
        } catch (NamingException e) {
            throw new ODMException("Cannot instantiate a session", e);
        }
    }
    return current.getKey();
}
项目:ARCLib    文件:DummySSLLdapContextSource.java   
@Override
protected DirContext getDirContextInstance(Hashtable<String, Object> env) throws NamingException {
    String url = (String) env.get(Context.PROVIDER_URL);
    try {
        if (new URI(url).getScheme().equalsIgnoreCase("ldaps")) {
            env.put("java.naming.ldap.factory.socket", "cz.inqool.uas.security.ldap.ssl.DummySSLSocketFactory");
        }
    } catch (URISyntaxException e) {
        log.error("LDAP URL {} is wrong", url, e);
    }
    return new InitialLdapContext(env, null);
}
项目:ServerlessPlatform    文件:AuthenticationService.java   
public static ArrayList<String> userList()
{
        loadAdmindetails();
        System.out.println("Details Loaded");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, url);
        props.put(Context.SECURITY_PRINCIPAL, "cn="+ldapadminuname+",dc=serverless,dc=com");//adminuser - User with special priviledge, dn user
        props.put(Context.SECURITY_CREDENTIALS, ldapadminpassword);//dn user password

        ArrayList<String> resp = new ArrayList<String>();
        try {
            LdapContext ctx = new InitialLdapContext(props, null);
            ctx.setRequestControls(null);
            NamingEnumeration<?> namingEnum = ctx.search("ou=ias,dc=serverless,dc=com", "(objectclass=posixAccount)", AuthenticationService.getSimpleSearchControls());
            while (namingEnum.hasMore ()) {
                SearchResult result = (SearchResult) namingEnum.next ();    
                Attributes attrs = result.getAttributes ();
                resp.add(attrs.get("cn").toString().substring(4));
            } 
            namingEnum.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }
项目:ServerlessPlatform    文件:AuthenticationService.java   
public static ArrayList<String> userList()
{
        loadAdmindetails();
        System.out.println("Details Loaded");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, url);
        props.put(Context.SECURITY_PRINCIPAL, "cn="+ldapadminuname+",dc=serverless,dc=com");//adminuser - User with special priviledge, dn user
        props.put(Context.SECURITY_CREDENTIALS, ldapadminpassword);//dn user password

        ArrayList<String> resp = new ArrayList<String>();
        try {
            LdapContext ctx = new InitialLdapContext(props, null);
            ctx.setRequestControls(null);
            NamingEnumeration<?> namingEnum = ctx.search("ou=ias,dc=serverless,dc=com", "(objectclass=posixAccount)", AuthenticationService.getSimpleSearchControls());
            while (namingEnum.hasMore ()) {
                SearchResult result = (SearchResult) namingEnum.next ();    
                Attributes attrs = result.getAttributes ();
                resp.add(attrs.get("cn").toString().substring(4));
            } 
            namingEnum.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }
项目:openshift-ldapsync    文件:LdapServer.java   
public Attributes getByDn(final String dn) throws NamingException {
    LdapContext ctx = new InitialLdapContext(env, null);
    Attributes result = ctx.getAttributes(dn);
    ctx.close();

    return result;
}
项目:openshift-ldapsync    文件:LdapServer.java   
public NamingEnumeration<SearchResult> search(final String baseDN, final String filter) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<SearchResult> result = ctx.search(baseDN, filter, searchControls);
    ctx.close();

    return result;
}
项目:sonar-activedirectory    文件:ApacheDS.java   
@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
  Preconditions.checkState(ldapServer.isStarted());

  kdcServer.setDirectoryService(directoryService);
  // FIXME hard-coded ports
  kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
  kdcServer.setEnabled(true);
  kdcServer.setPrimaryRealm(realm);
  kdcServer.setSearchBaseDn(baseDn);
  kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
  kdcServer.start();

  // -------------------------------------------------------------------
  // Enable the krb5kdc schema
  // -------------------------------------------------------------------

  Hashtable<String, Object> env = new Hashtable<String, Object>();
  env.put(DirectoryService.JNDI_KEY, directoryService);
  env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
  env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
  InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

  // check if krb5kdc is disabled
  Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
  boolean isKrb5KdcDisabled = false;
  if (krb5kdcAttrs.get("m-disabled") != null) {
    isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
  }

  // if krb5kdc is disabled then enable it
  if (isKrb5KdcDisabled) {
    Attribute disabled = new BasicAttribute("m-disabled");
    ModificationItem[] mods = new ModificationItem[] {new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled)};
    schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
  }
  return this;
}
项目:neo4j-example-auth-plugins    文件:LdapGroupHasUsersAuthPlugin.java   
private LdapContext authenticate( String username, char[] password ) throws NamingException
{
    Hashtable<String,Object> env = new Hashtable<>();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
    env.put( Context.PROVIDER_URL, ldapServerUrl );
    env.put( Context.SECURITY_PRINCIPAL, String.format( "cn=%s,ou=users,dc=example,dc=com", username ) );
    env.put( Context.SECURITY_CREDENTIALS, password );

    return new InitialLdapContext( env, null );
}
项目:communote-server    文件:AbstractApacheDSServer.java   
/**
 * Common code to get an initial context via a simple bind to the server over the wire using the
 * SUN JNDI LDAP provider. Do not use this method until after the setUp() method is called to
 * start the server otherwise it will fail.
 *
 * @param bindPrincipalDn
 *            the DN of the principal to bind as
 * @param password
 *            the password of the bind principal
 * @return an LDAP context as the the administrator to the rootDSE
 * @throws Exception
 *             if the server cannot be contacted
 */
protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception {
    // if ( ! apacheDS.isStarted() )
    // {
    // throw new ConfigurationException( "The server is not online! Cannot connect to it." );
    // }

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + getPort());
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    return new InitialLdapContext(env, null);
}
项目:communote-server    文件:AbstractApacheDSServer.java   
/**
 * Sets the contexts of this class taking into account the extras and overrides properties.
 *
 * @param env
 *            an environment to use while setting up the system root.
 * @throws Exception
 *             if there is a failure of any kind
 */
protected void setContexts(Hashtable<String, Object> env) throws Exception {
    Hashtable<String, Object> envFinal = new Hashtable<String, Object>(env);
    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.SYSTEM_DN);
    setSysRoot(new InitialLdapContext(envFinal, null));

    envFinal.put(Context.PROVIDER_URL, "");
    setRootDSE(getDirectoryService().getAdminSession());

    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    setSchemaRoot(new InitialLdapContext(envFinal, null));
}
项目:Hue-Ctrip-DI    文件:LdapAuthenticate.java   
@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;
}
项目:picketbox    文件:LdapRolesMappingProvider.java   
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);
}
项目:picketbox    文件:LdapAttributeMappingProvider.java   
private 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);
}
项目:picketbox    文件:LdapUsersLoginModule.java   
/**
 * Bind to the LDAP server for authentication
 */
private boolean createLdapInitContext(String username, Object credential) throws Exception
{
   // Get the admin context for searching
   InitialLdapContext ctx = null;
   ClassLoader currentTCCL = SecurityActions.getContextClassLoader();
   try
   {
      if (currentTCCL != null)
         SecurityActions.setContextClassLoader(null);
      ctx = constructInitialLdapContext(bindDN, bindCredential);
      // Validate the user by binding against the userDN
      bindDNAuthentication(ctx, username, credential, baseDN, baseFilter);
   }
   catch(Exception e)
   {
      throw e;
   }
finally
   {
      if (ctx != null)
         ctx.close();
      if (currentTCCL != null)
         SecurityActions.setContextClassLoader(currentTCCL);
   }
   return true;
}
项目:picketbox    文件:LdapUsersLoginModule.java   
@SuppressWarnings("rawtypes")
private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
{
   Properties env = new Properties();
   Iterator iter = options.entrySet().iterator();
   while (iter.hasNext())
   {
      Entry entry = (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);
}
项目:picketbox    文件:LdapExtLoginModule.java   
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);
}
项目:picketbox    文件:LdapCallbackHandler.java   
protected void verifyPassword( VerifyPasswordCallback vpc) throws NamingException
{
    String credential = vpc.getValue();

    ClassLoader currentTCCL = SecurityActions.getContextClassLoader();
    if (currentTCCL != null)
        SecurityActions.setContextClassLoader(null);

    String  baseDN = options.get(BASE_CTX_DN);
    String  baseFilter = options.get(BASE_FILTER_OPT);

    InitialLdapContext ctx= this.constructInitialLdapContext(bindDN, bindCredential);
    bindDNAuthentication(ctx, userName, credential, baseDN, baseFilter);
    vpc.setVerified(true);
}
项目:picketbox    文件:LdapCallbackHandler.java   
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);
}
项目:picketbox    文件:LdapCallbackHandler.java   
protected void safeClose(InitialLdapContext ic)
{
    if(ic != null)
    {
        try
        {
            ic.close();
        }
        catch (NamingException e)
        {
        }
    }
}
项目:federated-login-ext    文件:LDAPUtil.java   
public LDAPUtil(String ldapURL, String rootSearch) {
    this.rootSearch = rootSearch;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    try {

        this.ctx = new InitialLdapContext(env, null);
    } catch (NamingException ex) {
        _log.error(ex);
    }
}
项目:juddi    文件:LdapSimpleAuthenticator.java   
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;
    }
}
项目:juddi    文件:LdapExpandedAuthenticator.java   
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;
    }
}
项目:glowroot    文件:LdapAuthentication.java   
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);
}