Search in sources :

Example 1 with AuthenticationException

use of javax.naming.AuthenticationException in project zeppelin by apache.

the class LdapRealm method getRoles.

private Set<String> getRoles(PrincipalCollection principals, final LdapContextFactory ldapContextFactory) throws NamingException {
    final String username = (String) getAvailablePrincipal(principals);
    LdapContext systemLdapCtx = null;
    try {
        systemLdapCtx = ldapContextFactory.getSystemLdapContext();
        return rolesFor(principals, username, systemLdapCtx, ldapContextFactory);
    } catch (AuthenticationException ae) {
        ae.printStackTrace();
        return Collections.emptySet();
    } finally {
        LdapUtils.closeContext(systemLdapCtx);
    }
}
Also used : AuthenticationException(javax.naming.AuthenticationException) LdapContext(javax.naming.ldap.LdapContext)

Example 2 with AuthenticationException

use of javax.naming.AuthenticationException in project jforum2 by rafaelsteil.

the class LDAPAuthenticator method validateLogin.

/**
	 * @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String, java.util.Map)
	 */
public User validateLogin(String username, String password, Map extraParams) {
    Hashtable environment = this.prepareEnvironment();
    StringBuffer principal = new StringBuffer(256).append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX)).append(username).append(',').append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX));
    environment.put(Context.SECURITY_PRINCIPAL, principal.toString());
    environment.put(Context.SECURITY_CREDENTIALS, password);
    DirContext dir = null;
    try {
        dir = new InitialDirContext(environment);
        String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX);
        String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX);
        if (lookupPrefix == null || lookupPrefix.length() == 0) {
            lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX);
        }
        if (lookupSuffix == null || lookupSuffix.length() == 0) {
            lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX);
        }
        String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix;
        Attribute att = dir.getAttributes(lookupPrincipal).get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL));
        SSOUtils utils = new SSOUtils();
        if (!utils.userExists(username)) {
            String email = att != null ? (String) att.get() : "noemail";
            utils.register("ldap", email);
        }
        return utils.getUser();
    } catch (AuthenticationException e) {
        return null;
    } catch (NamingException e) {
        return null;
    } finally {
        if (dir != null) {
            try {
                dir.close();
            } catch (NamingException e) {
            //close jndi context
            }
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) AuthenticationException(javax.naming.AuthenticationException) Hashtable(java.util.Hashtable) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 3 with AuthenticationException

use of javax.naming.AuthenticationException in project pulsar by yahoo.

the class ServerCnx method handleConnect.

@Override
protected void handleConnect(CommandConnect connect) {
    checkArgument(state == State.Start);
    if (service.isAuthenticationEnabled()) {
        try {
            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();
}
Also used : AuthenticationDataCommand(com.yahoo.pulsar.broker.authentication.AuthenticationDataCommand) AuthenticationException(javax.naming.AuthenticationException) SSLSession(javax.net.ssl.SSLSession) ChannelHandler(io.netty.channel.ChannelHandler) SslHandler(io.netty.handler.ssl.SslHandler)

Example 4 with AuthenticationException

use of javax.naming.AuthenticationException in project pulsar by yahoo.

the class ServerCnxTest method testConnectCommandWithAuthenticationNegative.

@Test(timeOut = 30000)
public void testConnectCommandWithAuthenticationNegative() throws Exception {
    AuthenticationException e = new AuthenticationException();
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    doReturn(authenticationService).when(brokerService).getAuthenticationService();
    doThrow(e).when(authenticationService).authenticate(new AuthenticationDataCommand(Mockito.anyString()), Mockito.anyString());
    doReturn(true).when(brokerService).isAuthenticationEnabled();
    resetChannel();
    assertTrue(channel.isActive());
    assertEquals(serverCnx.getState(), State.Start);
    // test server response to CONNECT
    ByteBuf clientCommand = Commands.newConnect("none", "");
    channel.writeInbound(clientCommand);
    assertEquals(serverCnx.getState(), State.Start);
    assertTrue(getResponse() instanceof CommandError);
    channel.finish();
}
Also used : AuthenticationDataCommand(com.yahoo.pulsar.broker.authentication.AuthenticationDataCommand) AuthenticationException(javax.naming.AuthenticationException) CommandError(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandError) ByteBuf(io.netty.buffer.ByteBuf) AuthenticationService(com.yahoo.pulsar.broker.authentication.AuthenticationService) Test(org.testng.annotations.Test)

Example 5 with AuthenticationException

use of javax.naming.AuthenticationException in project uPortal by Jasig.

the class SimpleLdapSecurityContext method authenticate.

/** Authenticates the user. */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;
    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();
    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;
        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        log.debug("SimpleLdapSecurityContext: Looking for {}", user.toString());
        try {
            conn = ldapConn.getConnection();
            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore()) {
                            log.error("SimpleLdapSecurityContext: user not found: {}", this.myPrincipal.UID);
                        }
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in {} for {}", dnBuffer.toString(), attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);
                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User {} ({}) is authenticated", this.myPrincipal.UID, this.myPrincipal.FullName);
                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        }
                    // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: {}", this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavailable");
            }
        } catch (final NamingException ne) {
            log.error("Error getting connection to LDAP server.", ne);
        }
    } else {
        // If the principal and/or credential are missing, the context authentication
        // simply fails. It should not be construed that this is an error. It happens for guest access.
        log.info("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}
Also used : ILdapServer(org.apereo.portal.ldap.ILdapServer) AuthenticationException(javax.naming.AuthenticationException) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Aggregations

AuthenticationException (javax.naming.AuthenticationException)15 NamingException (javax.naming.NamingException)5 AuthenticationDataCommand (com.yahoo.pulsar.broker.authentication.AuthenticationDataCommand)3 Hashtable (java.util.Hashtable)3 ChannelHandler (io.netty.channel.ChannelHandler)2 SslHandler (io.netty.handler.ssl.SslHandler)2 RemoteException (java.rmi.RemoteException)2 Attributes (javax.naming.directory.Attributes)2 DirContext (javax.naming.directory.DirContext)2 SearchControls (javax.naming.directory.SearchControls)2 SearchResult (javax.naming.directory.SearchResult)2 LdapContext (javax.naming.ldap.LdapContext)2 SSLSession (javax.net.ssl.SSLSession)2 LoginException (javax.security.auth.login.LoginException)2 SecurityService (org.apache.openejb.spi.SecurityService)2 LdapResult (com.sun.jndi.ldap.LdapResult)1 RoleToken (com.yahoo.athenz.auth.token.RoleToken)1 AuthenticationService (com.yahoo.pulsar.broker.authentication.AuthenticationService)1 CommandError (com.yahoo.pulsar.common.api.proto.PulsarApi.CommandError)1 ByteBuf (io.netty.buffer.ByteBuf)1