Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

In this page you can find the example usage for javax.naming Context SECURITY_PRINCIPAL.

Prototype

String SECURITY_PRINCIPAL

To view the source code for javax.naming Context SECURITY_PRINCIPAL.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the identity of the principal for authenticating the caller to the service.

Usage

From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }//  w  ww  . jav  a  2  s  . co m

    boolean isLdapUser = false;

    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        logger.error("config exception! " + authorizedName, ex);
    }

    try {
        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
        String format = String.format(
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_LDAP_EXPANDED_STR),
                authorizedName);

        env.put(Context.SECURITY_PRINCIPAL, format);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher was not found, adding the publisher in on the fly.");
                publisher = new Publisher();
                publisher.setAuthorizedName(authorizedName);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(MaxBindingsPerService);
                publisher.setMaxBusinesses(MaxBusinesses);
                publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
                publisher.setMaxTmodels(MaxTmodels);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Creates an LDAP authenticator for the specified server, base DN and given
 * identifier attribute//from ww w. j  av a 2s .c  o m
 * 
 * @param baseUrl
 *            LDAP server URL
 * @param baseDn
 *            LDAP base DN
 * @param ldapSecurityPrincipal
 *            LDAP Security Principal
 * @param ldapSecurityCredentials
 *            Credentials for Security Principal
 * @param ldapRoleAttr
 *            Name of the LDAP attribute that defines the role
 * @param idAttr
 *            LDAP user identifier attribute
 */
public CustomLdapAuthenticationHandler(String baseUrl, String baseDn, String ldapSecurityPrincipal,
        String ldapSecurityCredentials, String ldapRoleAttr, String idAttr) {
    // Set public variables      
    this.baseDn = baseDn;
    this.idAttr = idAttr;
    this.ldapRoleAttr = ldapRoleAttr;
    this.baseUrl = baseUrl;
    this.ldapSecurityPrincipal = ldapSecurityPrincipal;
    this.ldapSecurityCredentials = ldapSecurityCredentials;
    if (CustomLdapAuthenticationHandler.credentialCache == null) {
        CacheManager singletonManager = CacheManager.create();
        CustomLdapAuthenticationHandler.credentialCache = new Cache("credentialCache", 500, false, false, 3600,
                1800);
        singletonManager.addCache(CustomLdapAuthenticationHandler.credentialCache);
    }

    // Initialise the LDAP environment
    env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, baseUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (!ldapSecurityPrincipal.equals("")) {
        env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
        env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);
    }

}

From source file:org.apache.juddi.v3.auth.LdapSimpleAuthenticator.java

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }/* w w  w.j a v  a  2  s.  com*/

    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        logger.error("config exception! " + authorizedName, ex);
    }
    boolean isLdapUser = false;
    try {
        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
        env.put(Context.SECURITY_PRINCIPAL, authorizedName);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher was not found, adding the publisher in on the fly.");
                publisher = new Publisher();
                publisher.setAuthorizedName(authorizedName);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(MaxBindingsPerService);
                publisher.setMaxBusinesses(MaxBusinesses);
                publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
                publisher.setMaxTmodels(MaxTmodels);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

From source file:com.mirth.connect.connectors.jms.JmsReceiverTests.java

private static ConnectionFactory lookupConnectionFactoryWithJndi(JmsConnectorProperties connectorProperties)
        throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.PROVIDER_URL, connectorProperties.getJndiProviderUrl());
    env.put(Context.INITIAL_CONTEXT_FACTORY, connectorProperties.getJndiInitialContextFactory());
    env.put(Context.SECURITY_PRINCIPAL, connectorProperties.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, connectorProperties.getPassword());

    initialContext = new InitialContext(env);
    String connectionFactoryName = connectorProperties.getJndiConnectionFactoryName();
    return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

@Override
public void configure(String id, Properties properties) throws PIPException {
    /*/*from  ww  w .j a  va  2  s  .c o m*/
     * Handle the standard properties
     */
    super.configure(id, properties);
    String propertyPrefix = id + ".";

    /*
     * Configure the LDAP environment: I think the only required property is the provider_url
     */
    if (!this.configureStringProperty(propertyPrefix, Context.PROVIDER_URL, properties, null)) {
        throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                + propertyPrefix + Context.PROVIDER_URL);
    }
    this.configureStringProperty(propertyPrefix, Context.AUTHORITATIVE, properties, null);
    this.configureIntegerProperty(propertyPrefix, Context.BATCHSIZE, properties, null);
    this.configureStringProperty(propertyPrefix, Context.DNS_URL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.INITIAL_CONTEXT_FACTORY, properties,
            DEFAULT_CONTEXT_FACTORY);
    this.configureStringProperty(propertyPrefix, Context.LANGUAGE, properties, null);
    this.configureStringProperty(propertyPrefix, Context.OBJECT_FACTORIES, properties, null);
    this.configureStringProperty(propertyPrefix, Context.REFERRAL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_AUTHENTICATION, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_CREDENTIALS, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_PRINCIPAL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_PROTOCOL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.STATE_FACTORIES, properties, null);
    this.configureStringProperty(propertyPrefix, Context.URL_PKG_PREFIXES, properties, null);

    String ldapScopeValue = properties.getProperty(propertyPrefix + PROP_LDAP_SCOPE, DEFAULT_SCOPE);
    if (LDAP_SCOPE_SUBTREE.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.SUBTREE_SCOPE;
    } else if (LDAP_SCOPE_OBJECT.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.OBJECT_SCOPE;
    } else if (LDAP_SCOPE_ONELEVEL.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.ONELEVEL_SCOPE;
    } else {
        this.logger.warn("Invalid LDAP Scope value '" + ldapScopeValue + "'; using " + DEFAULT_SCOPE);
        this.ldapScope = SearchControls.SUBTREE_SCOPE;
    }

    /*
     * Get list of resolvers defined for this LDAP Engine
     */
    String resolversList = properties.getProperty(propertyPrefix + PROP_RESOLVERS);
    if (resolversList == null || resolversList.isEmpty()) {
        throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                + propertyPrefix + PROP_RESOLVERS);
    }

    /*
     * Iterate the resolvers
     */
    for (String resolver : Splitter.on(',').trimResults().omitEmptyStrings().split(resolversList)) {
        /*
         * Get the LDAPResolver for this LDAPEngine
         */
        String resolverClassName = properties
                .getProperty(propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname");
        if (resolverClassName == null) {
            throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                    + propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname");
        }

        LDAPResolver ldapResolverNew = null;
        try {
            Class<?> classResolver = Class.forName(resolverClassName);
            if (!LDAPResolver.class.isAssignableFrom(classResolver)) {
                this.logger.error("LDAPResolver class " + resolverClassName + " does not implement "
                        + LDAPResolver.class.getCanonicalName());
                throw new PIPException("LDAPResolver class " + resolverClassName + " does not implement "
                        + LDAPResolver.class.getCanonicalName());
            }
            ldapResolverNew = LDAPResolver.class.cast(classResolver.newInstance());
        } catch (Exception ex) {
            this.logger.error("Exception instantiating LDAPResolver for class '" + resolverClassName + "': "
                    + ex.getMessage(), ex);
            throw new PIPException("Exception instantiating LDAPResolver for class '" + resolverClassName + "'",
                    ex);
        }
        assert ldapResolverNew != null;
        ldapResolverNew.configure(propertyPrefix + PROP_RESOLVER + "." + resolver, properties,
                this.getIssuer());

        this.ldapResolvers.add(ldapResolverNew);
    }

}

From source file:ldap.SearchUtility.java

/**
 * open the directory connection.//from   ww w .  j a va 2s  .c  om
 *
 * @param url
 * @param tracing
 * @return
 * @throws javax.naming.NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
    * First, set up a large number of environment variables to sensible default valuse
    */

    Hashtable env = new Hashtable();
    // sanity check
    if (url == null)
        throw new NamingException("URL not specified in openContext()!");

    // set the tracing level now, since it can't be set once the connection is open.
    if (tracing)
        env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output

    env.put("java.naming.ldap.version", "3"); // always use ldap v3 - v2 too limited
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // use default jndi provider
    env.put("java.naming.ldap.deleteRDN", "false"); // usually what we want
    env.put(Context.REFERRAL, "ignore"); //could be: follow, ignore, throw
    env.put("java.naming.ldap.derefAliases", "finding"); // could be: finding, searching, etc.
    env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 'simple' = username + password
    env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn
    env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-
    env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

    /*
    *  Open the actual LDAP session using the above environment variables
    */

    DirContext newContext = new InitialDirContext(env);

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

    return newContext;

}

From source file:com.aurel.track.util.LdapUtil.java

public static boolean authenticate(TSiteBean siteBean, String loginName, String ppassword)
        throws NamingException {
    boolean userIsOK = false;
    ArrayList<String> trace = new ArrayList<String>();

    trace.add("Ldap trying to authenticate user with loginname >" + loginName + "<");

    if (siteBean.getLdapServerURL().startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
    }/*from   w w  w .ja v  a2  s  . c o  m*/
    // get the CN
    String keyDn = getCn(siteBean, loginName);

    try {
        if (keyDn != null) {
            trace.add("Using keyDn >" + keyDn + "<");
            // Set up the environment for creating the initial context
            Hashtable<String, String> env = new Hashtable<String, String>(11);
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, siteBean.getLdapServerURL());
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, keyDn);
            env.put(Context.SECURITY_CREDENTIALS, ppassword);
            // Create initial context
            DirContext itest = new InitialDirContext(env);
            itest.close();
            // user was validated
            userIsOK = true;
        }
        return userIsOK;
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.warn(msg);
        }
        throw e;
    }
}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static DirContext getDirContext(BehavioralContext bctx, Object principal, Object credentials)
        throws NamingException {
    DirContext ctx = null;/*from  w  ww  .j ava  2  s .c  om*/

    Configuration tconfig = bctx.getConfig();
    String ldapProvider = "ldap" + "://" + tconfig.getString(Constants.KEY_AD_HOST) + ":"
            + tconfig.getString(Constants.KEY_AD_PORT) + "/" + tconfig.getString(Constants.KEY_AD_ROOT_DN);

    log.info("Using LDAP url: [" + ldapProvider + "]");

    //        String url, String contextFactoryName,

    Hashtable jndiEnv = new Hashtable();

    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    jndiEnv.put(Context.PROVIDER_URL, ldapProvider);
    jndiEnv.put(Context.REFERRAL, "follow");

    if (tconfig.getBoolean(Constants.KEY_AD_SSL)) {
        log.info("Using SSL for LDAP");
        jndiEnv.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    jndiEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (principal != null)
        jndiEnv.put(Context.SECURITY_PRINCIPAL, principal);

    if (credentials != null)
        jndiEnv.put(Context.SECURITY_CREDENTIALS, credentials);

    try {
        // Creating the JNDI directory context (with LDAP context
        // factory), performs an LDAP bind to the LDAP provider thereby
        // authenticating the username/pw.
        ctx = new InitialDirContext(jndiEnv);
    } catch (NamingException ex) {
        log.error("Directory context init failed", ex);
        throw ex;
    }

    return ctx;
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public boolean authenticate(String userDN, String password) throws NamingException {
    Hashtable<String, Object> props = new Hashtable<String, Object>(env);
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.SECURITY_PRINCIPAL, userDN);
    props.put(Context.SECURITY_CREDENTIALS, password);
    props.put("com.sun.jndi.ldap.connect.pool", "false");

    InitialContext ctx = null;//from  w w  w . j  a  v a 2  s .c om
    try {
        ctx = new DummyLdapContext(new InitialLdapContext(props, null));
        return true;
    } catch (NamingException e) {
        LOG.debug("Error during initialization LDAP Context", e);
        return false;
    } finally {
        closeContext(ctx);
    }
}

From source file:LDAPTest.java

/**
     * Gets a context from the properties specified in the file ldapserver.properties
     * @return the directory context/*from   w  ww. ja  va2s . c  o m*/
     */
    public static DirContext getContext() throws NamingException, IOException {
        Properties props = new Properties();
        FileInputStream in = new FileInputStream("ldapserver.properties");
        props.load(in);
        in.close();

        String url = props.getProperty("ldap.url");
        String username = props.getProperty("ldap.username");
        String password = props.getProperty("ldap.password");

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext initial = new InitialDirContext(env);
        DirContext context = (DirContext) initial.lookup(url);

        return context;
    }