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.nuxeo.ecm.directory.ldap.MockLdapServer.java

public void startLdapServer() {
    cfg = new MutableStartupConfiguration();
    cfg.setWorkingDirectory(workingDir);

    log.debug("Working directory is " + workingDir.getAbsolutePath());

    Properties env = new Properties();

    env.setProperty(Context.PROVIDER_URL, BASE_DN);
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    env.setProperty(Context.SECURITY_PRINCIPAL, PartitionNexus.ADMIN_PRINCIPAL);
    env.setProperty(Context.SECURITY_CREDENTIALS, PartitionNexus.ADMIN_PASSWORD);

    try {//from w  w  w . j  ava 2 s .co m
        initConfiguration();
        env.putAll(cfg.toJndiEnvironment());
        serverContext = new InitialDirContext(env);
    } catch (NamingException e) {
        log.error("Failed to start Apache DS: ", e);
    }
}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

private DirContext createAuthenticatedContext() {
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userName);
    env.put(Context.SECURITY_CREDENTIALS, password);
    return createContext(env);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Opens a connection to Active Directory by establishing an initial LDAP
 * context.  The security principal and credentials are assigned the
 * account name and password parameters.
 *
 * @param anAcountDN Active Directory account name (DN format).
 * @param anAccountPassword Active Directory account password.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from  ww  w.ja  v a  2s  .c  o m*/
@SuppressWarnings("unchecked")
public void open(String anAcountDN, String anAccountPassword) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "open");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // LDAP Reference - http://docs.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html

    Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
    environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
    environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
    environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentalVariables.put(Context.SECURITY_PRINCIPAL, anAcountDN);
    environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);

    // Referral options: follow, throw, ignore (default)

    environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));

    // Authentication options: simple, DIGEST-MD5 CRAM-MD5

    environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple"));

    try {
        mLdapContext = new InitialLdapContext(environmentalVariables, null);
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Context Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:jp.terasoluna.fw.web.jndi.DefaultJndiSupport.java

/**
 * JndiTemplate??//from  w  ww.j a va  2s  .  com
 */
public void initialize() {

    // JNDI???????Weblogic??
    if (jndiEnvironmentMap != null) {

        // jndiEnvironmentMap???
        String factory = jndiEnvironmentMap.get(JNDI_FACTORY_KEY);
        String url = jndiEnvironmentMap.get(JNDI_URL_KEY);
        String username = jndiEnvironmentMap.get(JNDI_USERNAME_KEY);
        String password = jndiEnvironmentMap.get(JNDI_PASSWORD_KEY);

        Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        environment.put(Context.PROVIDER_URL, url);

        if (!"".equals(username) && username != null) {
            environment.put(Context.SECURITY_PRINCIPAL, username);
            if (password == null) {
                password = "";
            }
            environment.put(Context.SECURITY_CREDENTIALS, password);
        }

        // ??
        getJndiTemplate().setEnvironment(environment);

        // 
        if (log.isInfoEnabled()) {
            log.info("Initialize Weblogic JNDI Resource");
            log.info(Context.INITIAL_CONTEXT_FACTORY + " = " + factory);
            log.info(Context.PROVIDER_URL + " = " + url);
            log.info(Context.SECURITY_PRINCIPAL + " = " + username);
            log.info(Context.SECURITY_CREDENTIALS + " = " + password);
        }
    }
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

private DirContext createAuthenticatedContext() {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userName);
    env.put(Context.SECURITY_CREDENTIALS, password);
    return createContext(env);
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Check if connection with login and password possible.
 *
 * @param user/*w  ww  .j  av  a2  s.c o  m*/
 *            User object
 * @param password
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User user, String password) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());

    // Start TLS
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {
        logger.debug("use TLS for auth");
        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, buildUserDN(user));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            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.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), 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, buildUserDN(user));
            env.put(Context.SECURITY_CREDENTIALS, password);
        }
        logger.debug("ldap environment set");

        try {
            logger.debug("start classic ldap authentication");
            logger.debug("user DN is {}", buildUserDN(user));

            if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == 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(buildUserDN(user));
                Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
            return false;
        }
    }
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

/**
 * Changes the password for the current user. The username is obtained from the security
 * context. <p> If the old password is supplied, the update will be made by rebinding as the
 * user, thus modifying the password using the user's permissions. If <code>oldPassword</code>
 * is null, the update will be attempted using a standard read/write context supplied by the
 * context source. </p>//w w  w.jav  a  2  s  .  co m
 *
 * @param oldPassword the old password
 * @param newPassword the new value of the password.
 */
public void changePassword(final String oldPassword, final String newPassword) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Assert.notNull(authentication,
            "No authentication object found in security context. Can't change current user's password!");

    String username = authentication.getName();

    logger.debug("Changing password for user '" + username);

    final DistinguishedName dn = usernameMapper.buildDn(username);
    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };

    if (oldPassword == null) {
        template.modifyAttributes(dn, passwordChange);
        return;
    }

    template.executeReadWrite(new ContextExecutor() {

        public Object executeWithContext(DirContext dirCtx) throws NamingException {
            LdapContext ctx = (LdapContext) dirCtx;
            ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(dn, ctx).toString());
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
            // TODO: reconnect doesn't appear to actually change the
            // credentials
            try {
                ctx.reconnect(null);
            } catch (javax.naming.AuthenticationException e) {
                throw new BadCredentialsException("Authentication for password change failed.");
            }

            ctx.modifyAttributes(dn, passwordChange);

            return null;
        }
    });
}

From source file:org.lsc.jndi.JndiServices.java

private void initConnection() throws NamingException, IOException {
    // log new connection with it's details
    logConnectingTo(connProps);//www.  jav a 2s . c o m

    /* should we negotiate TLS? */
    if (connProps.get(TLS_CONFIGURATION) != null && (Boolean) connProps.get(TLS_CONFIGURATION)) {
        /* if we're going to do TLS, we mustn't BIND before the STARTTLS operation
         * so we remove credentials from the properties to stop JNDI from binding */
        /* duplicate properties to avoid changing them (they are used as a cache key in getInstance() */
        Properties localConnProps = new Properties();
        localConnProps.putAll(connProps);
        String jndiContextAuthentication = localConnProps.getProperty(Context.SECURITY_AUTHENTICATION);
        String jndiContextPrincipal = localConnProps.getProperty(Context.SECURITY_PRINCIPAL);
        String jndiContextCredentials = localConnProps.getProperty(Context.SECURITY_CREDENTIALS);
        localConnProps.remove(Context.SECURITY_AUTHENTICATION);
        localConnProps.remove(Context.SECURITY_PRINCIPAL);
        localConnProps.remove(Context.SECURITY_CREDENTIALS);

        /* open the connection */
        ctx = new InitialLdapContext(localConnProps, null);

        /* initiate the STARTTLS extended operation */
        try {
            tlsResponse = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tlsResponse.negotiate();
        } catch (IOException e) {
            LOGGER.error("Error starting TLS encryption on connection to {}",
                    localConnProps.getProperty(Context.PROVIDER_URL));
            LOGGER.debug(e.toString(), e);
            throw e;
        } catch (NamingException e) {
            LOGGER.error("Error starting TLS encryption on connection to {}",
                    localConnProps.getProperty(Context.PROVIDER_URL));
            LOGGER.debug(e.toString(), e);
            throw e;
        }

        /* now we add the credentials back to the context, to BIND once TLS is started */
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiContextAuthentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, jndiContextPrincipal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, jndiContextCredentials);

    } else {
        /* don't start TLS, just connect normally (this can be on ldap:// or ldaps://) */
        ctx = new InitialLdapContext(connProps, null);
    }

    /* get LDAP naming context */
    try {
        namingContext = new LdapUrl((String) ctx.getEnvironment().get(Context.PROVIDER_URL));
    } catch (LdapURLEncodingException e) {
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
        throw new NamingException(e.getMessage());
    }

    /* handle options */
    contextDn = namingContext.getDn() != null ? namingContext.getDn() : null;

    String pageSizeStr = (String) ctx.getEnvironment().get("java.naming.ldap.pageSize");
    if (pageSizeStr != null) {
        pageSize = Integer.parseInt(pageSizeStr);
    } else {
        pageSize = -1;
    }

    sortedBy = (String) ctx.getEnvironment().get("java.naming.ldap.sortedBy");

    String recursiveDeleteStr = (String) ctx.getEnvironment().get("java.naming.recursivedelete");
    if (recursiveDeleteStr != null) {
        recursiveDelete = Boolean.parseBoolean(recursiveDeleteStr);
    } else {
        recursiveDelete = false;
    }

    /* Load SyncRepl response control */
    LdapApiService ldapApiService = LdapApiServiceFactory.getSingleton();
    ControlFactory<?> factory = new SyncStateValueFactory(ldapApiService);
    ldapApiService.registerControl(factory);
    /* Load Persistent Search response control */
    factory = new PersistentSearchFactory(ldapApiService);
    ldapApiService.registerControl(factory);
}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPBindIdentityStore.java

/**
 * This store performs a bind to the configured LDAP server and closes the connection immediately.
 * If the connection fails, an exception is thrown, otherwise this method returns silentrly
 *
 * @return true if the bind is successful
 *//* w w  w  .  j a v a2s.co m*/
public boolean bind(String username, String password, BindContext bindCtx) throws SSOAuthenticationException {

    String dn = null;

    try {

        // first try to retrieve the user using an known user
        dn = selectUserDN(username);
        if (dn == null || "".equals(dn)) {
            if (logger.isDebugEnabled())
                logger.debug("No DN found for user : " + username);
            return false;
        }
        logger.debug("user dn = " + dn);

        // Create context without binding!
        InitialLdapContext ctx = this.createLdapInitialContext(null, null);
        Control[] ldapControls = null;

        try {

            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);

            if (isPasswordPolicySupport()) {
                // Configure request control for password policy:
                ctx.reconnect(new Control[] { new BasicControl(PasswordPolicyResponseControl.CONTROL_OID) });
            } else {
                ctx.reconnect(new Control[] {});
            }

            // Get response controls from reconnect BEFORE dn search, or they're lost
            ldapControls = ctx.getResponseControls();

            // Bind to LDAP an check for authentication warning/errors reported in password policy control:
            if (validateBindWithSearch) {
                selectUserDN(ctx, username);

                // Perhaps controls are not send during reconnet, try to get them now
                if (ldapControls == null || ldapControls.length == 0)
                    ldapControls = ctx.getResponseControls();
            }

            if (logger.isTraceEnabled())
                logger.trace("LDAP Bind with user credentials succeeded");

        } catch (AuthenticationException e) {

            if (logger.isDebugEnabled())
                logger.debug("LDAP Bind Authentication error : " + e.getMessage(), e);

            return false;

        } finally {

            if (isPasswordPolicySupport()) {

                // If an exception occurred, controls are not retrieved yet
                if (ldapControls == null || ldapControls.length == 0)
                    ldapControls = ctx.getResponseControls();

                // Check password policy LDAP Control
                PasswordPolicyResponseControl ppolicyCtrl = decodePasswordPolicyControl(ldapControls);
                if (ppolicyCtrl != null)
                    addPasswordPolicyToBindCtx(ppolicyCtrl, bindCtx);

            }

            ctx.close();
        }

        return true;

    } catch (Exception e) {
        throw new SSOAuthenticationException(
                "Cannot bind as user : " + username + " [" + dn + "]" + e.getMessage(), e);
    }

}