Create a directory context.

@param principal The principal name to bind with.
@param credential The password / credential.
@return The {@link TimedDirContext} of the new connection.
@throws NamingException If the bind failed.
516323
@FFDCIgnore(NamingException.class)
    public TimedDirContext createDirContext(String principal, byte[] credential) throws NamingException {
        final String METHODNAME = "createDirContext(String, byte[])";

        String activeURL = getActiveURL();
        Hashtable<String, Object> environment = getEnvironment(URLTYPE_SINGLE, activeURL);
        environment.put(Context.SECURITY_PRINCIPAL, principal);
        environment.put(Context.SECURITY_CREDENTIALS, credential);

        SSLUtilImpl sslUtil = new SSLUtilImpl();
        Properties currentSSLProps = sslUtil.getSSLPropertiesOnThread();
        try {
            if (iSSLAlias != null) {
                try {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, METHODNAME + " Use WAS SSL Configuration.");
                    sslUtil.setSSLAlias(iSSLAlias, environment);
                } catch (Exception ssle) {
                    throw new NamingException(ssle.getMessage());
                }
            }

            // Set the classloader so that a class in the package can be loaded by JNDI
            ClassLoader origCL = getContextClassLoader();
            setContextClassLoader(getClass());
            try {
                TimedDirContext ctx = null;
                try {
                    ctx = new TimedDirContext(environment, getConnectionRequestControls(), roundToSeconds(System.currentTimeMillis()));
                } catch (NamingException e) {
                    if (!isConnectionException(e)) {
                        throw e;
                    } else {
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "Encountered an exception while creating a context: " + e.getMessage());
                    }

                    // Get the Next URL
                    environment = getEnvironment(URLTYPE_SEQUENCE, getNextURL(activeURL));
                    // Reset the security credentials on the environment.
                    environment.put(Context.SECURITY_PRINCIPAL, principal);
                    environment.put(Context.SECURITY_CREDENTIALS, credential);

                    ctx = new TimedDirContext(environment, getConnectionRequestControls(), roundToSeconds(System.currentTimeMillis()));
                    String newURL = getProviderURL(ctx);
                    long creationTimeMillisec = System.currentTimeMillis();

                    synchronized (iLock) {
                        // Refresh context pool if another thread hasn't already done so
                        if (creationTimeMillisec > iPoolCreateTimestampMillisec) {
                            createContextPool(iLiveContexts, newURL);
                            ctx.setCreateTimestamp(iPoolCreateTimestampSeconds);
                        }
                    }
                }
                return ctx;
            } finally {
                setContextClassLoader(origCL);
            }
        } finally {
            sslUtil.setSSLPropertiesOnThread(currentSSLProps);
        }
    }
1197996
public void map(final UserResource user, final Principal p,
                    final Credential credential) {
        user.setUserName(p.getId());
        if (credential instanceof UsernamePasswordCredential) {
            user.setPassword(UsernamePasswordCredential.class.cast(credential).getPassword());
        }
        user.setActive(Boolean.TRUE);

        user.setNickName(getPrincipalAttributeValue(p, "nickName"));
        user.setDisplayName(getPrincipalAttributeValue(p, "displayName"));

        val name = new Name(getPrincipalAttributeValue(p, "formattedName"),
            getPrincipalAttributeValue(p, "familyName"),
            getPrincipalAttributeValue(p, "middleName"),
            getPrincipalAttributeValue(p, "givenName"),
            getPrincipalAttributeValue(p, "honorificPrefix"),
            getPrincipalAttributeValue(p, "honorificSuffix"));
        user.setName(name);

        val entry = new Entry(getPrincipalAttributeValue(p, "mail"), "primary");
        user.setEmails(CollectionUtils.wrap(entry));

        val entry2 = new Entry(getPrincipalAttributeValue(p, "phoneNumber"), "primary");
        user.setPhoneNumbers(CollectionUtils.wrap(entry2));
    }
232023
private static DirContext getDirContext() {
        Hashtable<String, String> env = new Hashtable<>();
        env.put(JAVA_NAMING_FACTORY_INITIAL, DNS_NAMING_FACTORY);
        env.put(JAVA_NAMING_PROVIDER_URL, DNS_PROVIDER_URL);

        try {
            return new InitialDirContext(env);
        } catch (Throwable e) {
            throw new RuntimeException("Cannot get dir context for some reason", e);
        }
    }
639506
@SneakyThrows
    protected boolean updateUserResource(final UserResource user, final Principal p, final Credential credential) {
        this.mapper.map(user, p, credential);
        return endpoint.update(user) != null;
    }
1023067
public Principal createUser(final SecurityContext securityContext, final PropertyKey credentialKey, final String credentialValue, final String confKey) {

		return createUser(securityContext, credentialKey, credentialValue, Collections.EMPTY_MAP, confKey);

	}
863850
public void setContextParameters(
            Map<String, String> principals,
            Map<String, String> credentials,
            String ctxName,
            ISecurityContext securityContext) {

        if (log.isDebugEnabled()) {
            final StringBuilder msg = new StringBuilder();
            msg.append("Preparing to authenticate;  setting parameters for context name '")
                    .append(ctxName)
                    .append("', context class '")
                    .append(securityContext.getClass().getName())
                    .append("'");
            // Display principalTokens...
            msg.append("\n\t Available Principal Tokens");
            for (final Object o : principals.entrySet()) {
                final Map.Entry<?, ?> y = (Map.Entry<?, ?>) o;
                msg.append("\n\t\t").append(y.getKey()).append("=").append(y.getValue());
            }
            // Keep credentialTokens secret, but indicate whether they were provided...
            msg.append("\n\t Available Credential Tokens");
            for (final Object o : credentials.entrySet()) {
                final Map.Entry<?, ?> y = (Map.Entry<?, ?>) o;
                final String val = (String) y.getValue();
                String valWasSpecified = null;
                if (val != null) {
                    valWasSpecified = val.trim().length() == 0 ? "empty" : "provided";
                }
                msg.append("\n\t\t").append(y.getKey()).append(" was ").append(valWasSpecified);
            }
            log.debug(msg.toString());
        }

        String username = principals.get(ctxName);
        String credential = credentials.get(ctxName);
        // If username or credential are null, this indicates that the token was not
        // set in security.properties. We will then use the value for root.
        username = username != null ? username : (String) principals.get(BASE_CONTEXT_NAME);
        credential = credential != null ? credential : (String) credentials.get(BASE_CONTEXT_NAME);
        if (log.isDebugEnabled()) {
            log.debug("Authentication::setContextParameters() username: " + username);
        }
        // Retrieve and populate an instance of the principal object
        final IPrincipal principalInstance = securityContext.getPrincipalInstance();
        if (username != null && !username.equals("")) {
            principalInstance.setUID(username);
        }
        // Retrieve and populate an instance of the credentials object
        final IOpaqueCredentials credentialsInstance =
                securityContext.getOpaqueCredentialsInstance();
        if (credentialsInstance != null) {
            credentialsInstance.setCredentials(credential);
        }
    }
396778
private ManagedConnectionPool getManagedConnectionPool(Credential credential)
   {
      ManagedConnectionPool mcp = pools.get(credential);

      if (mcp == null)
      {
         synchronized (this)
         {
            mcp = pools.get(credential);

            if (mcp == null)
            {
               ManagedConnectionPool newMcp = createManagedConnectionPool(credential);
               mcp = pools.putIfAbsent(credential, newMcp);
               if (mcp == null)
               {
                  mcp = newMcp;

                  if (Tracer.isEnabled())
                     Tracer.createManagedConnectionPool(poolConfiguration.getId(), mcp);
               }
               else
               {
                  newMcp.shutdown();
               }
            }
         }
      }
      return mcp;
   }
1349454
public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, String principalName) {

        CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
        I_CmsPrincipal result = null;
        try {
            result = m_driverManager.lookupPrincipal(dbc, CmsOrganizationalUnit.removeLeadingSeparator(principalName));
        } finally {
            dbc.clear();
        }
        return result;
    }
96527
@Override
    public JMSContext createContext(int sessionMode) throws JMSRuntimeException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "createContext", new Object[] { sessionMode });

        JmsJMSContextImpl jmsContext = null;

        // If the context created is container-managed, then JMSRuntimeException must be thrown
        if (jmsConnection.isManaged()) {
            JMSException jmse = (JMSException) JmsErrorUtils.newThrowable(JMSException.class,
                                                                          "CREATECONTEXT_IN_CONTAINER_CWSIA0513",
                                                                          null, tc);
            throw (JMSRuntimeException) JmsErrorUtils.getJMS2Exception(jmse, JMSRuntimeException.class);
        }

        try {
            //CTS test failure was reported when the session mode was passed as -1,  so adding the validation
            switch (sessionMode)
            {
                case JMSContext.AUTO_ACKNOWLEDGE:
                case JMSContext.CLIENT_ACKNOWLEDGE:
                case JMSContext.DUPS_OK_ACKNOWLEDGE:
                case JMSContext.SESSION_TRANSACTED: {
                    break;
                }
                default:
                    throw (JMSRuntimeException) JmsErrorUtils.newThrowable(JMSRuntimeException.class,
                                                                           "INVALID_ACKNOWLEDGE_MODE_CWSIA0514",
                                                                           new Object[] {},
                                                                           tc
                                    );
            }

            jmsContext = new JmsJMSContextImpl(jmsConnection, sessionMode, false);
        } finally {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "createContext", new Object[] { jmsContext });
        }
        return jmsContext;
    }
1228217
public void setAuthenticated(final String sessionId, final Principal user) {

		securityContext = SecurityContext.getInstance(user, AccessMode.Backend);
		securityContext.setSessionId(sessionId);

		logger.debug("Session ID of security context " + securityContext + " set to " + sessionId);

		timedOut = false;
	}
500384
public void preProcess(DirContext ctx) throws NamingException {
        for (DirContextProcessor processor : dirContextProcessors) {
            processor.preProcess(ctx);
        }
    }
174736
public static void bindCurrent(final Credential... credentials) {
        CURRENT_CREDENTIAL_IDS.set(Arrays.stream(credentials).map(Credential::getId).toArray(String[]::new));
    }
1089299
public void setSingleSignOn(HttpRequest request,
                                HttpResponse response,
                                Principal principal,
                                Credential credential)
    {
        
        String ssoID=null;
        
        synchronized(_ssoId2Principal)
        {
            // Create new SSO ID
            while (true)
            {
                ssoID = Long.toString(Math.abs(_random.nextLong()),
                                      30 + (int)(System.currentTimeMillis() % 7));
                if (!_ssoId2Principal.containsKey(ssoID))
                    break;
            }
            
            if(log.isDebugEnabled())log.debug("set ssoID="+ssoID);
            _ssoId2Principal.put(ssoID,principal);
            _ssoPrincipal2Credential.put(principal,credential);
            _ssoUsername2Id.put(principal.getName(),ssoID);
        }
        
        Cookie cookie = new Cookie(SSO_COOKIE_NAME, ssoID);
        cookie.setPath("/");
        response.addSetCookie(cookie);
    }
1196501
public SdkClientBuilder proxyCredentials(String user, String password) {
        this.proxyCredentials = new UsernamePasswordCredentials(user, password);
        return this;
    }
640679
public OvhCredential api_credential_credentialId_GET(Long credentialId) throws IOException {
		String qPath = "/me/api/credential/{credentialId}";
		StringBuilder sb = path(qPath, credentialId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhCredential.class);
	}
570146
@SuppressWarnings({ "rawtypes", "unchecked" })
   protected DirContext setupKerberosContext(Hashtable<String,Object> env) 
   throws NamingException
   {

      LoginContext lc = null;
      try
      {

    	 lc = new LoginContext(getClass().getName(), new JXCallbackHandler());
         lc.login();

      }
      catch (LoginException ex)
      {
         throw new NamingException("login problem: " + ex);
      }

      DirContext ctx = (DirContext) Subject.doAs(lc.getSubject(), new JndiAction(env));

      if (ctx == null)
         throw new NamingException("another problem with GSSAPI");
      else
         return ctx;
    
   }
1371817
public static boolean isAuthenticed(String host, int port, String userName, String password) throws NamingException {
		log.info("isAuthenticed");
		// Set up the environment for creating the initial context
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, userName + "@" + host);
		log.info(env.toString());
		env.put(Context.SECURITY_CREDENTIALS, password);
		// Create the initial context
		DirContext ctx = new InitialDirContext(env);
		log.info("DirContext Init Succ");
		boolean result = ctx != null;
		if (ctx != null) {
			log.info("Closing DirContext");
			ctx.close();
		}
		return result;
	}