Example usage for javax.naming Context SECURITY_CREDENTIALS

List of usage examples for javax.naming Context SECURITY_CREDENTIALS

Introduction

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

Prototype

String SECURITY_CREDENTIALS

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

Click Source Link

Document

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

Usage

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testUserMethod() throws Exception {
    log.debug("+++ testUserMethod()");
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    env.setProperty(Context.SECURITY_PRINCIPAL, "jduke");
    env.setProperty(Context.SECURITY_CREDENTIALS, "theduke");
    InitialContext ctx = new InitialContext(env);
    Object obj = ctx.lookup("jacc/Secured");
    obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class);
    SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj;
    log.debug("Found SecuredServiceRemoteHome");
    SecuredServiceRemote bean = home.create();
    log.debug("Created SecuredServiceRemote");

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);
    bean.userMethod(info);/* w  ww  . j  a  v a2 s  .  c o m*/
    bean.remove();
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

private boolean bindUser(DirContext context, String dn, String password) throws NamingException {
    boolean isValid = false;
    context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
    context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
    try {//from  w  w  w. ja  va2s.  c  o  m
        context.getAttributes("", null);
        isValid = true;
    } catch (AuthenticationException e) {
    }
    if (StringUtils.isNotEmpty(this.username)) {
        context.addToEnvironment(Context.SECURITY_PRINCIPAL, this.username);
    } else {
        context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
    }
    if (StringUtils.isNotEmpty(this.password)) {
        context.addToEnvironment(Context.SECURITY_CREDENTIALS, this.password);
    } else {
        context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
    }
    return isValid;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer/*w ww.  j a  v  a2s. co m*/
 *            User object
 * @param inPasswort
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = getLdapConnectionSettings();

    // Start TLS
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {
        logger.debug("use TLS for auth");
        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            env.put(Context.SECURITY_CREDENTIALS, inPasswort);
        }
        logger.debug("ldap environment set");

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("start classic ldap authentification");
                logger.debug("user DN is " + getUserDN(inBenutzer));
            }

            if (ConfigCore.getParameter("ldap_AttributeToTest") == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
                Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest"));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("login not allowed for " + inBenutzer.getLogin(), e);
            }
            return false;
        }
    }
}

From source file:org.apache.synapse.message.store.impl.jdbc.util.JDBCConfiguration.java

/**
 * Lookup the DataSource on JNDI using the specified name and optional properties
 *
 * @return a DataSource looked up using the specified JNDI properties
 *//*from  ww w . j ava 2  s  . co  m*/
private DataSource lookupDataSource() {
    DataSource dataSource = null;
    RepositoryBasedDataSourceFinder finder = DataSourceRepositoryHolder.getInstance()
            .getRepositoryBasedDataSourceFinder();

    if (finder.isInitialized()) {
        // First try a lookup based on the data source name only
        dataSource = finder.find(dataSourceName);
    }
    if (dataSource == null) {
        // Decrypt the password if needed
        String password = jndiProperties.getProperty(Context.SECURITY_CREDENTIALS);
        if (password != null && !"".equals(password)) {
            jndiProperties.put(Context.SECURITY_CREDENTIALS, getActualPassword(password));
        }
        // Lookup the data source using the specified jndi properties
        dataSource = DataSourceFinder.find(dataSourceName, jndiProperties);
        if (dataSource == null) {
            handleException("Cannot find a DataSource " + dataSourceName + " for given JNDI" + " properties :"
                    + jndiProperties);
        }
    }
    if (dataSource != null) {
        log.info("Successfully looked up datasource " + dataSourceName);
    }
    return dataSource;
}

From source file:org.apache.axis2.transport.jms.JMSEndpoint.java

/**
 * Get the EPR for the given JMS connection factory and destination
 * the form of the URL is/*from www  .  j a  v  a  2  s.c  om*/
 * jms:/<destination>?[<key>=<value>&]*
 * Credentials Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS
 * JMSConstants.PARAM_JMS_USERNAME and JMSConstants.PARAM_JMS_USERNAME are filtered
 *
 * @return the EPR as a String
 */
private String getEPR() {
    StringBuffer sb = new StringBuffer();

    sb.append(JMSConstants.JMS_PREFIX).append(jndiDestinationName);
    sb.append("?").append(JMSConstants.PARAM_DEST_TYPE).append("=")
            .append(destinationType == JMSConstants.TOPIC ? JMSConstants.DESTINATION_TYPE_TOPIC
                    : JMSConstants.DESTINATION_TYPE_QUEUE);

    if (contentTypeRuleSet != null) {
        String contentTypeProperty = contentTypeRuleSet.getDefaultContentTypeProperty();
        if (contentTypeProperty != null) {
            sb.append("&");
            sb.append(JMSConstants.CONTENT_TYPE_PROPERTY_PARAM);
            sb.append("=");
            sb.append(contentTypeProperty);
        }
    }

    for (Map.Entry<String, String> entry : cf.getParameters().entrySet()) {
        if (!Context.SECURITY_PRINCIPAL.equalsIgnoreCase(entry.getKey())
                && !Context.SECURITY_CREDENTIALS.equalsIgnoreCase(entry.getKey())
                && !JMSConstants.PARAM_JMS_USERNAME.equalsIgnoreCase(entry.getKey())
                && !JMSConstants.PARAM_JMS_PASSWORD.equalsIgnoreCase(entry.getKey())) {
            sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
    }
    return sb.toString();
}

From source file:CreateJavaSchema.java

/**
 * Signs on to directory server using parameters supplied to program.
 * @return The initial context to the server.
 */// w  w  w  .  j  a v  a2 s  . co  m
private DirContext signOn() throws NamingException {
    if (dn != null && auth == null) {
        auth = "simple"; // use simple for Netscape
    }

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.REFERRAL, "follow");

    if (auth != null) {
        env.put(Context.SECURITY_AUTHENTICATION, auth);
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
    }

    // Workaround for Netscape schema bugs
    if (netscapebug) {
        env.put("com.sun.naming.netscape.schemaBugs", "true");
    }

    // LDAP protocol tracing
    if (traceLdap) {
        env.put("com.sun.jndi.ldap.trace.ber", System.err);
    }

    return new InitialDirContext(env);
}

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));
    }//  www  . j a  va 2  s.  c  om

    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  www. j a  v  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.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

@Override
public void configure(String id, Properties properties) throws PIPException {
    /*//from w w  w  . ja  v  a2 s  .c om
     * 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: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));
    }//from ww w.  j  a  va 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;
}