Example usage for javax.security.auth.login LoginException initCause

List of usage examples for javax.security.auth.login LoginException initCause

Introduction

In this page you can find the example usage for javax.security.auth.login LoginException initCause.

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java

@Override
public PrincipalId authenticate(PrincipalId principal, String password) throws LoginException {
    ValidateUtil.validateNotNull(principal, "principal");

    IIdmAuthStatRecorder idmAuthStatRecorder = this.createIdmAuthStatRecorderInstance(
            DiagnosticsContextFactory.getCurrentDiagnosticsContext().getTenantName(), ActivityKind.AUTHENTICATE,
            EventLevel.INFO, principal);
    idmAuthStatRecorder.start();//from   w  ww.j a  v a 2  s  .c o m

    principal = this.normalizeAliasInPrincipal(principal);
    InvalidCredentialsLdapException srpEx = null;
    try {
        ILdapConnectionEx connection = null;
        try {
            connection = this.getConnection(principal.getUPN(), password, AuthenticationType.SRP, false);
        } catch (InvalidCredentialsLdapException ex) {
            logger.warn("Failed to authenticate using SRP binding", ex);
            srpEx = ex;
        } finally {
            if (connection != null) {
                connection.close();
                connection = null;
            }
        }
        if (srpEx != null) {
            String userDn = getUserDn(principal, true);
            if (userDn != null) {
                try {
                    logger.warn("The user is not SRP-enabled. Attempting to authenticate using simple bind.");
                    connection = this.getConnection(userDn, password, AuthenticationType.PASSWORD, false);
                } finally {
                    if (connection != null) {
                        connection.close();
                        connection = null;
                    }
                }
            } else {
                logger.warn("The user is SRP-enabled and failed to authenticate.");
                throw srpEx;
            }
        }
    } catch (Exception ex) {
        final LoginException loginException = new LoginException("Login failed");
        loginException.initCause(ex);
        throw loginException;
    }

    idmAuthStatRecorder.end();

    return principal;
}

From source file:org.apache.ranger.authentication.unix.jaas.PamLoginModule.java

private void createPam(String service) throws LoginException {
    try {/*from  w  ww  .  jav  a2  s  . c  o m*/
        _pam = new PAM(service);
    } catch (PAMException ex) {
        LoginException le = new LoginException("Error initializing PAM");
        le.initCause(ex);
        throw le;
    }
}

From source file:org.apache.ranger.authentication.unix.jaas.PamLoginModule.java

private void obtainUserAndPassword() throws LoginException {
    if (_callbackHandler == null) {
        throw new LoginException(
                "Error: no CallbackHandler available  to gather authentication information from the user");
    }//ww  w  .  jav  a 2  s  .co m

    try {
        NameCallback nameCallback = new NameCallback("username");
        PasswordCallback passwordCallback = new PasswordCallback("password", false);

        invokeCallbackHandler(nameCallback, passwordCallback);

        initUserName(nameCallback);
        initPassword(passwordCallback);
    } catch (IOException | UnsupportedCallbackException ex) {
        LoginException le = new LoginException("Error in callbacks");
        le.initCause(ex);
        throw le;
    }
}

From source file:org.apache.ranger.authentication.unix.jaas.PamLoginModule.java

private boolean performLogin() throws LoginException {
    try {/*from  ww w  . j  av a 2s  . co  m*/
        if (StringUtils.isNotEmpty(_password)) {
            UnixUser user = _pam.authenticate(_username, _password);
            _principal = new PamPrincipal(user);
            _authSucceeded = true;
            return true;
        } else {
            throw new PAMException("Password is Null or Empty!!!");
        }
    } catch (PAMException ex) {
        LoginException le = new FailedLoginException("Invalid username or password");
        le.initCause(ex);
        throw le;
    }
}

From source file:org.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java

/**
 * /*from   w ww . ja v  a  2 s .  c om*/
 * TAKEN FROM Jboss class
 *  
 * org.jboss.security.auth.spi.UsernamePasswordLoginModule
 * 
 * and adjust it to Astroboa requirements
 * 
 * @return
 * @throws LoginException
 */
private String[] getAuthenticationInformation() throws LoginException {
    String[] info = { null, null, null, null, null };
    // prompt for a username and password
    if (callbackHandler == null) {
        throw new LoginException(
                "Error: no CallbackHandler available " + "to collect authentication information");
    }

    NameCallback nc = new NameCallback("User name: ", "guest");
    PasswordCallback pc = new PasswordCallback("Password: ", false);
    AstroboaAuthenticationCallback authenticationCallback = new AstroboaAuthenticationCallback(
            "Astroboa authentication info");

    Callback[] callbacks = { nc, pc, authenticationCallback };
    String username = null;
    String password = null;
    String identityStoreLocation = null;
    String userSecretKey = null;
    String repositoryId = null;

    try {
        callbackHandler.handle(callbacks);
        username = nc.getName();
        char[] tmpPassword = pc.getPassword();
        if (tmpPassword != null) {
            char[] credential = new char[tmpPassword.length];
            System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
            pc.clearPassword();
            password = new String(credential);
        }

        identityStoreLocation = authenticationCallback.getIdentityStoreLocation();

        useExternalIdentity = authenticationCallback.isExternalIdentityStore();

        userSecretKey = authenticationCallback.getSecretKey();

        repositoryId = authenticationCallback.getRepositoryId();
    } catch (IOException e) {
        LoginException le = new LoginException("Failed to get username/password");
        le.initCause(e);
        throw le;
    } catch (UnsupportedCallbackException e) {
        LoginException le = new LoginException("CallbackHandler does not support: " + e.getCallback());
        le.initCause(e);
        throw le;
    }
    info[0] = username;
    info[1] = password;
    info[2] = userSecretKey;
    info[3] = identityStoreLocation;
    info[4] = repositoryId;

    return info;
}

From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java

@Override
public String getUsersPassword(String username) throws LoginException {

    String password = null;//from   ww w .j  av a  2  s.c  o m
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        // Get the password
        if (logger.isDebugEnabled()) {
            logger.debug("Executing query: " + principalsQuery + ", with username: " + username);
        }
        ps = conn.prepareStatement(principalsQuery);
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next() == false) {
            if (logger.isDebugEnabled()) {
                logger.debug(principalsQuery + " returned no matches from db");
            }
            throw new FailedLoginException("No matching username found");
        }

        password = rs.getString(1);
    } catch (SQLException ex) {
        LoginException le = new LoginException("Query failed");
        le.initCause(ex);
        throw le;
    } catch (Exception ex) {
        LoginException le = new LoginException("Unknown Exception");
        le.initCause(ex);
        throw le;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
            }
        }
    }
    return password;
}

From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java

/**
 * Execute the rolesQuery against the datasourceName to obtain the roles for
 * the authenticated user./*from www.  j a v a 2 s .  co m*/
 * @return collection containing the roles
 */
@Override
public Collection<Group> getRoles(String username, String principalClassName, String groupClassName)
        throws LoginException {

    if (logger.isDebugEnabled()) {
        logger.debug("getRoleSets using rolesQuery: " + rolesQuery + ", username: " + username);
    }

    Connection conn = null;
    HashMap<String, Group> groupsMap = new HashMap<String, Group>();
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        conn = getConnection();
        // Get the user role names
        if (logger.isDebugEnabled()) {
            logger.debug("Executing query: " + rolesQuery + ", with username: " + username);
        }

        ps = conn.prepareStatement(rolesQuery);
        try {
            ps.setString(1, username);
        } catch (ArrayIndexOutOfBoundsException ignore) {
            // The query may not have any parameters so just try it
        }
        rs = ps.executeQuery();
        if (rs.next() == false) {
            if (logger.isDebugEnabled()) {
                logger.debug("No roles found");
            }
            //                if(aslm.getUnauthenticatedIdentity() == null){
            //                    throw new FailedLoginException("No matching username found in Roles");
            //                }
            /* We are running with an unauthenticatedIdentity so create an
            empty Roles set and return.
             */

            Group g = createGroup(groupClassName, "Roles");
            groupsMap.put(g.getName(), g);
            return groupsMap.values();
        }

        do {
            String roleName = rs.getString(1);
            String groupName = rs.getString(2);
            if (groupName == null || groupName.length() == 0) {
                groupName = "Roles";
            }

            Group group = (Group) groupsMap.get(groupName);
            if (group == null) {
                group = createGroup(groupClassName, groupName);
                groupsMap.put(groupName, group);
            }

            try {
                Principal p = createPrincipal(principalClassName, roleName);
                if (logger.isDebugEnabled()) {
                    logger.debug("Assign user to role " + roleName);
                }

                group.addMember(p);
            } catch (Exception e) {
                logger.error("Failed to create principal: " + roleName + " " + e.toString());
            }

        } while (rs.next());
    } catch (SQLException ex) {
        LoginException le = new LoginException("Query failed");
        le.initCause(ex);
        throw le;
    } catch (Exception e) {
        LoginException le = new LoginException("unknown exception");
        le.initCause(e);
        throw le;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
            }
        }

    }

    return groupsMap.values();

}

From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java

/**
 * Execute the tenantsQuery against the datasourceName to obtain the tenants for
 * the authenticated user.//ww  w. j av a 2  s.c om
 * @return collection containing the roles
 */
@Override
public Collection<Group> getTenants(String username, String groupClassName) throws LoginException {

    if (logger.isDebugEnabled()) {
        logger.debug("getTenants using tenantsQuery: " + tenantsQuery + ", username: " + username);
    }

    Connection conn = null;
    HashMap<String, Group> groupsMap = new HashMap<String, Group>();
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        conn = getConnection();
        // Get the user role names
        if (logger.isDebugEnabled()) {
            logger.debug("Executing query: " + tenantsQuery + ", with username: " + username);
        }

        ps = conn.prepareStatement(tenantsQuery);
        try {
            ps.setString(1, username);
        } catch (ArrayIndexOutOfBoundsException ignore) {
            // The query may not have any parameters so just try it
        }
        rs = ps.executeQuery();
        if (rs.next() == false) {
            if (logger.isDebugEnabled()) {
                logger.debug("No tenants found");
            }
            // We are running with an unauthenticatedIdentity so create an
            // empty Tenants set and return.
            // FIXME  should this be allowed?
            Group g = createGroup(groupClassName, "Tenants");
            groupsMap.put(g.getName(), g);
            return groupsMap.values();
        }

        do {
            String tenantId = rs.getString(1);
            String tenantName = rs.getString(2);
            String groupName = rs.getString(3);
            if (groupName == null || groupName.length() == 0) {
                groupName = "Tenants";
            }

            Group group = (Group) groupsMap.get(groupName);
            if (group == null) {
                group = createGroup(groupClassName, groupName);
                groupsMap.put(groupName, group);
            }

            try {
                Principal p = createTenant(tenantName, tenantId);
                if (logger.isDebugEnabled()) {
                    logger.debug("Assign user to tenant " + tenantName);
                }

                group.addMember(p);
            } catch (Exception e) {
                logger.error("Failed to create tenant: " + tenantName + " " + e.toString());
            }
        } while (rs.next());
    } catch (SQLException ex) {
        LoginException le = new LoginException("Query failed");
        le.initCause(ex);
        throw le;
    } catch (Exception e) {
        LoginException le = new LoginException("unknown exception");
        le.initCause(e);
        throw le;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
            }
        }

    }

    return groupsMap.values();
}

From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java

private Connection getConnection() throws LoginException, SQLException {
    InitialContext ctx = null;//from w  w w.j a va2  s.  c o m
    Connection conn = null;
    try {
        ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup(getDataSourceName());
        if (ds == null) {
            throw new IllegalArgumentException("datasource not found: " + getDataSourceName());
        }
        conn = ds.getConnection();
        return conn;
    } catch (NamingException ex) {
        LoginException le = new LoginException("Error looking up DataSource from: " + getDataSourceName());
        le.initCause(ex);
        throw le;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
            }
        }
    }

}

From source file:org.marketcetera.client.MockLoginModule.java

@Override
public boolean login() throws LoginException {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Name");
    callbacks[1] = new PasswordCallback("Password", false);
    try {//from   w  w w .ja  va2  s  .  co  m
        callback.handle(callbacks);
    } catch (UnsupportedCallbackException e) {
        final LoginException ex = new FailedLoginException(e.getMessage());
        ex.initCause(e);
        throw ex;
    } catch (IOException e) {
        final LoginException ex = new FailedLoginException(e.getMessage());
        ex.initCause(e);
        throw ex;
    }
    username = ((NameCallback) callbacks[0]).getName();
    char[] password = ((PasswordCallback) callbacks[1]).getPassword();
    String pass = String.valueOf(password);
    if (!ObjectUtils.equals(username, pass)) {
        throw new FailedLoginException(username + "<>" + pass);
    }
    SLF4JLoggerProxy.debug(this, "login done for user {}", username); //$NON-NLS-1$
    return true;
}