Example usage for javax.naming AuthenticationException getMessage

List of usage examples for javax.naming AuthenticationException getMessage

Introduction

In this page you can find the example usage for javax.naming AuthenticationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:br.com.upic.camel.ldap.LdapEndpoint.java

@Override
protected void onExchange(final Exchange exchange) throws Exception {
    LOG.info("Setting up the context");

    final Hashtable<String, String> conf = new Hashtable<String, String>();

    LOG.debug("Initial Context Factory = " + initialContextFactory);

    conf.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);

    LOG.debug("Provider URL = " + providerUrl);

    conf.put(Context.PROVIDER_URL, providerUrl);

    LOG.debug("Security Authentication = " + securityAuthentication);

    conf.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);

    final Message in = exchange.getIn();

    final String user = in.getHeader(HEADER_USER, String.class);

    LOG.debug("User = " + user);

    conf.put(Context.SECURITY_PRINCIPAL, user);

    final String password = in.getHeader(HEADER_PASSWORD, String.class);

    LOG.debug("Password = " + password);

    conf.put(Context.SECURITY_CREDENTIALS, password);

    LOG.info("Authenticating in directory");

    final Message out = exchange.getOut();

    try {//from   w w  w . j  a  v  a 2  s  .  com
        new InitialContext(conf);

        out.setBody(true);
    } catch (final AuthenticationException e) {
        LOG.error(e.getMessage(), e);

        out.setBody(false);
    }

}

From source file:gda.jython.authenticator.LdapAuthenticator.java

private boolean checkAuthenticatedUsingServer(String ldapURL, String fedId, String password)
        throws NamingException {

    InitialLdapContext ctx = null;
    try {//w w w  .jav a  2 s  . c om
        Hashtable<String, String> env = new Hashtable<String, String>();
        String principal = "CN=" + fedId + adminName;
        env.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, ldapURL);
        ctx = new InitialLdapContext(env, null);
        //if no exception then password is OK
        return true;
    } catch (AuthenticationException ae) {
        logger.error("LDAP AuthenticationException: " + StringEscapeUtils.escapeJava(ae.getMessage()));
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return false;
}

From source file:Core.Security.CustomEntryPoint.java

public void commence(final HttpServletRequest request, final HttpServletResponse response,
        final AuthenticationException authException) throws IOException, ServletException {
    //Authentication failed, send error response.
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
    PrintWriter writer = response.getWriter();
    writer.println("HTTP Status 401 : " + authException.getMessage());
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * Setup environment./* ww w  .  j a va2  s  .co  m*/
 * @param props 
 * @throws SourceUnavailableException
 */
protected void setupEnvironment(Properties props) throws SourceUnavailableException {
    this.environment.put("com.sun.jndi.ldap.connect.pool", "true");

    this.environment.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("INITIAL_CONTEXT_FACTORY"));
    this.environment.put(Context.PROVIDER_URL, props.getProperty("PROVIDER_URL"));
    this.environment.put(Context.SECURITY_AUTHENTICATION, props.getProperty("SECURITY_AUTHENTICATION"));
    this.environment.put(Context.SECURITY_PRINCIPAL, props.getProperty("SECURITY_PRINCIPAL"));

    String password = props.getProperty("SECURITY_CREDENTIALS");
    password = Morph.decryptIfFile(password);

    this.environment.put(Context.SECURITY_CREDENTIALS, password);
    if (props.getProperty("SECURITY_PROTOCOL") != null) {
        this.environment.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    Context context = null;
    try {
        log.debug("Creating Directory Context");
        context = new InitialDirContext(this.environment);
    } catch (AuthenticationException ex) {
        log.error("Error with Authentication " + ex.getMessage(), ex);
        throw new SourceUnavailableException("Error with Authentication ", ex);
    } catch (NamingException ex) {
        log.error("Naming Error " + ex.getMessage(), ex);
        throw new SourceUnavailableException("Naming Error", ex);
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    log.info("Success in connecting to LDAP");

    this.nameAttributeName = props.getProperty("Name_AttributeType");
    if (this.nameAttributeName == null) {
        log.error("Name_AttributeType not defined");
    }
    this.subjectIDAttributeName = props.getProperty("SubjectID_AttributeType");
    if (this.subjectIDAttributeName == null) {
        log.error("SubjectID_AttributeType not defined");
    }
    this.descriptionAttributeName = props.getProperty("Description_AttributeType");
    if (this.descriptionAttributeName == null) {
        log.error("Description_AttributeType not defined");
    }

}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * /*ww  w . j  a va  2s  .co  m*/
 * @param search
 * @param searchValue
 * @param attributeNames
 * @return naming enumeration
 */
protected NamingEnumeration getLdapResults(Search search, String searchValue, String[] attributeNames) {
    DirContext context = null;
    NamingEnumeration results = null;
    String filter = search.getParam("filter");
    if (filter == null) {
        log.error("Search filter not found for search type:  " + search.getSearchType());
        return results;
    }
    filter = filter.replaceAll("%TERM%", escapeSearchFilter(searchValue));
    String base = search.getParam("base");
    if (base == null) {
        base = "";
        log.error("Search base not found for:  " + search.getSearchType() + ". Using base \"\" ");

    }
    int scopeNum = -1;
    String scope = search.getParam("scope");
    if (scope != null) {
        scopeNum = getScope(scope);
    }
    if (scopeNum == -1) {
        scopeNum = SearchControls.SUBTREE_SCOPE;
        log.error("Search scope not found for: " + search.getSearchType() + ". Using scope SUBTREE_SCOPE.");
    }
    log.debug("searchType: " + search.getSearchType() + " filter: " + filter + " base: " + base + " scope: "
            + scope);
    try {
        context = new InitialDirContext(this.environment);
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(scopeNum);
        constraints.setReturningAttributes(attributeNames);
        results = context.search(base, filter, constraints);
    } catch (AuthenticationException ex) {
        log.error("Ldap Authentication Exception: " + ex.getMessage(), ex);
    } catch (NamingException ex) {
        log.error("Ldap NamingException: " + ex.getMessage(), ex);

    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ne) {
                // squelch, since it is already closed
            }
        }
    }
    return results;

}

From source file:ldap.ActiveLoginImpl.java

/**
   * Active Directory does not allow 'compare' ldap operations against passwords, so we either
   * use AD specific code (bad) or do a fake bind request (slow).  This uses the fake bind request;
   * for high performance enterprise apps a different approach is necessary (but enterprise apps would not
   * use AD, so it's a moot point).//  w ww.jav a  2  s .co  m
   *
   * @param login
   * @param password
   * @return whether the user login and password are valid.
   * @throws NamingException
   */
public boolean testBind(String login, String password, String userDN) throws NamingException {
    //String userDN = getUserDN(login);
    try {
        logger.info("Rebinding as user to test password");

        //setupJNDIConnection(Config.DIRECTORY_URL, userDN, password, verbose);
        setupJNDIConnection(LdapConstants.ldapDirectoryUrl, userDN, password, verbose);
        return true;
    } catch (AuthenticationException e) {
        //throw (e);
        logger.info(e.getMessage());
        return false;
    }
}

From source file:ldap.LdapApi.java

/**
 * openDirectoryConnection() - Open the directory connection for the executeAction() method to use.
 *//*  ww  w .  j av  a  2 s  .  c o  m*/
private DirContext openDirectoryConnection() throws NamingException {
    try {
        context = setupJNDIConnection(LdapConstants.ldapDirectoryUrl, LdapConstants.ldapDirectoryAdmin,
                LdapConstants.ldapDirectoryPwd, false);

    } catch (AuthenticationException e) {
        logger.info("There was an error establishing the 'admin' connection to the directory" + e.getMessage());
        logger.info("The directory rejected the administration credentials:");
        logger.info("   user: " + LdapConstants.ldapDirectoryAdmin);
        //logger.info("   pwd:  " + LdapConstants.ldapDirectoryPwd + "\n" + e.getMessage());
        logger.info("There was an error establishing the 'admin' connection to the directory", e);
        logger.info("  Examine the stack trace below for details, including the LDAP error message"
                + e.getMessage());
        throw e;
    }

    if (context == null) {
        logger.info("openDirectoryConnection(), context is null");
        //throw new LdapException("openDirectoryConnection(), Error: context is null");
    }
    return context;
}

From source file:com.yahoo.pulsar.broker.service.ServerCnx.java

@Override
protected void handleConnect(CommandConnect connect) {
    checkArgument(state == State.Start);
    if (service.isAuthenticationEnabled()) {
        try {/*from w  ww.j a v  a 2 s  . com*/
            String authMethod = "none";
            if (connect.hasAuthMethodName()) {
                authMethod = connect.getAuthMethodName();
            } else if (connect.hasAuthMethod()) {
                // Legacy client is passing enum
                authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
            }

            String authData = connect.getAuthData().toStringUtf8();
            ChannelHandler sslHandler = ctx.channel().pipeline().get(PulsarChannelInitializer.TLS_HANDLER);
            SSLSession sslSession = null;
            if (sslHandler != null) {
                sslSession = ((SslHandler) sslHandler).engine().getSession();
            }
            authRole = getBrokerService().getAuthenticationService().authenticate(
                    new AuthenticationDataCommand(authData, remoteAddress, sslSession), authMethod);

            log.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod,
                    authRole);
        } catch (AuthenticationException e) {
            String msg = "Unable to authenticate";
            log.warn("[{}] {}: {}", remoteAddress, msg, e.getMessage());
            ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg));
            close();
            return;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Received CONNECT from {}", remoteAddress);
    }
    ctx.writeAndFlush(Commands.newConnected(connect));
    state = State.Connected;
    remoteEndpointProtocolVersion = connect.getProtocolVersion();
    String version = connect.hasClientVersion() ? connect.getClientVersion() : null;
    if (isNotBlank(version) && !version.contains(" ") /* ignore default version: pulsar client */) {
        this.clientVersion = version;
    }
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

/**
* Returns the LDAP User Distinguished Name (DN) to use when acquiring an
* {@link javax.naming.ldap.LdapContext LdapContext} from the
* {@link LdapContextFactory}./*from w ww  .  ja  va 2  s. c om*/
* <p/>
* If the the {@link #getUserDnTemplate() userDnTemplate} property has been
* set, this implementation will construct the User DN by substituting the
* specified {@code principal} into the configured template. If the
* {@link #getUserDnTemplate() userDnTemplate} has not been set, the method
* argument will be returned directly (indicating that the submitted
* authentication token principal <em>is</em> the User DN).
*
* @param principal
*            the principal to substitute into the configured
*            {@link #getUserDnTemplate() userDnTemplate}.
* @return the constructed User DN to use at runtime when acquiring an
*         {@link javax.naming.ldap.LdapContext}.
* @throws IllegalArgumentException
*             if the method argument is null or empty
* @throws IllegalStateException
*             if the {@link #getUserDnTemplate userDnTemplate} has not been
*             set.
* @see LdapContextFactory#getLdapContext(Object, Object)
*/
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
    String userDn;
    String matchedPrincipal = matchPrincipal(principal);
    String userSearchBase = getUserSearchBase();
    String userSearchAttributeName = getUserSearchAttributeName();

    // If not searching use the userDnTemplate and return.
    if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null
            && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
        userDn = expandTemplate(userDnTemplate, matchedPrincipal);
        if (log.isDebugEnabled()) {
            log.debug("LDAP UserDN and Principal: " + userDn + "," + principal);
        }
        return userDn;
    }

    // Create the searchBase and searchFilter from config.
    String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
    String searchFilter = null;
    if (userSearchFilter == null) {
        if (userSearchAttributeName == null) {
            searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
        } else {
            searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(),
                    userSearchAttributeName,
                    expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal));
        }
    } else {
        searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
    }
    SearchControls searchControls = getUserSearchControls();

    // Search for userDn and return.
    LdapContext systemLdapCtx = null;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        systemLdapCtx = getContextFactory().getSystemLdapContext();
        if (log.isDebugEnabled()) {
            log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + ","
                    + userSearchScope);
        }
        searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
        // SearchResults contains all the entries in search scope
        if (searchResultEnum.hasMore()) {
            SearchResult searchResult = searchResultEnum.next();
            userDn = searchResult.getNameInNamespace();
            if (log.isDebugEnabled()) {
                log.debug("UserDN Returned,Principal: " + userDn + "," + principal);
            }
            return userDn;
        } else {
            throw new IllegalArgumentException("Illegal principal name: " + principal);
        }
    } catch (AuthenticationException ne) {
        ne.printStackTrace();
        throw new IllegalArgumentException("Illegal principal name: " + principal);
    } catch (NamingException ne) {
        throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage());
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } catch (NamingException ne) {
            // Ignore exception on close.
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
}

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
 *//*from  w  w w .  j a  va2  s .c o 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);
    }

}