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

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

Introduction

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

Prototype

public LoginException(String msg) 

Source Link

Document

Constructs a LoginException with the specified detail message.

Usage

From source file:org.betaconceptframework.astroboa.security.jaas.AstroboaLoginModule.java

private void loadPersonByUserName(String username) throws LoginException {

    if (loggedInPerson == null) {
        try {//  www .ja v a2  s .c  om

            loggedInPerson = identityStore.retrieveUser(username);

        } catch (Exception e) {
            logger.error("Problem when loading person for username " + username, e);
            throw new LoginException("Problem when loading person for username " + username);
        }

        if (loggedInPerson == null) {
            throw new AccountNotFoundException(username);
        }

    }
}

From source file:org.josso.wls10.agent.jaas.SSOGatewayLoginModuleImpl.java

/**
 * Retreives the list of roles associated to current principal
 *///from  w  w  w. j  a  va2  s.  c  om
protected WLSJOSSORole[] getRoleSets() throws LoginException {
    try {
        // obtain user roles principals and add it to the subject
        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        SSORole[] roles = im.findRolesBySSOSessionId(_requester, _currentSSOSessionId);
        WLSJOSSORole[] wlsRoles = new WLSJOSSORole[roles.length];

        for (int i = 0; i < roles.length; i++) {
            SSORole role = roles[i];
            WLSJOSSORole wlsRole = new WLSJOSSORole(role);
            wlsRoles[i] = wlsRole;
        }

        return wlsRoles;

    } catch (Exception e) {
        logger.error("Session login failed for Principal : " + _ssoUserPrincipal, e);
        throw new LoginException("Session login failed for Principal : " + _ssoUserPrincipal);
    }

}

From source file:com.adobe.gems.exampleidp.impl.JsonFileIdentityProvider.java

/**
 * Authenticates the user represented by the given credentials and returns it. If the user does not exist in this
 * provider, {@code null} is returned. If the authentication fails, a LoginException is thrown.
 *
 * @param credentials the credentials/*from www  .  jav  a 2 s.  c  o  m*/
 * @return the user or {@code null}
 * @throws ExternalIdentityException if an error occurs
 * @throws javax.security.auth.login.LoginException if the user could not be authenticated
 */
@CheckForNull
public ExternalUser authenticate(@Nonnull Credentials credentials)
        throws ExternalIdentityException, LoginException {
    if (!(credentials instanceof SimpleCredentials)) {
        throw new LoginException("invalid credentials class " + credentials.getClass());
    }
    try {
        // extract the user id from the credentials and lookup the user
        SimpleCredentials sc = (SimpleCredentials) credentials;
        JSONObject userObj = loadJSON().optJSONObject(sc.getUserID());

        // if the user does not exist, return null
        if (userObj == null) {
            log.debug("authenticate: user '{}' not found in json file", sc.getUserID());
            return null;
        }
        log.debug("authenticate: user '{}' found in json file.", sc.getUserID());

        // verify the password and throw login exception on mismatch
        String pwd = userObj.optString(PN_PASSWORD, "");
        if (pwd.equals(new String(sc.getPassword()))) {
            // if all good, return the user as external identity
            log.debug("authenticate: users '{}' credentials validated.", sc.getUserID());
            return createIdentity(sc.getUserID(), null, userObj, ExternalUser.class);
        } else {
            throw new LoginException("invalid user or password");
        }
    } catch (IOException e) {
        throw new ExternalIdentityException(e);
    } catch (JSONException e) {
        throw new ExternalIdentityException(e);
    }
}

From source file:com.fiveamsolutions.nci.commons.authentication.CommonsGridLoginModule.java

private String getDecryptedPassword() throws LoginException {
    try {/*w ww.  j  a  va  2s .  c  o  m*/
        StringEncrypter encrypter = new StringEncrypter();
        return encrypter.decrypt(gridServiceCredential);
    } catch (EncryptionException e) {
        LOG.warn("Unable to encrypt password: " + e.getMessage(), e);
    }
    throw new LoginException("Could not decrypt saved password");
}

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

private void loadPersonByUserName(String username) throws LoginException {

    if (loggedInPerson == null) {
        try {//from   w  w  w .  j  av  a2s.  c o  m

            loggedInPerson = getIdentityStore().retrieveUser(username);

        } catch (Exception e) {
            logger.error("Problem when loading person for username " + username, e);
            throw new LoginException("Problem when loading person for username " + username);
        }

        if (loggedInPerson == null) {
            throw new AccountNotFoundException(username);
        }

    }
}

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  a  v a  2s .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.josso.wls10.agent.jaas.SSOGatewayLoginModuleNoCustomPrincipalsImpl.java

/**
 * Retreives the list of roles associated to current principal
 *///w  ww  .  j  ava 2s  .c  o  m
protected WLSGroup[] getRoleSets() throws LoginException {
    try {
        // obtain user roles principals and add it to the subject
        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        SSORole[] roles = im.findRolesBySSOSessionId(_requester, _currentSSOSessionId);
        WLSGroup[] wlsRoles = new WLSGroupImpl[roles.length];

        for (int i = 0; i < roles.length; i++) {
            SSORole role = roles[i];
            WLSGroup wlsRole = new WLSGroupImpl(role.getName());
            wlsRoles[i] = wlsRole;
        }

        return wlsRoles;

    } catch (Exception e) {
        logger.error("Session login failed for Principal : " + _ssoUserPrincipal, e);
        throw new LoginException("Session login failed for Principal : " + _ssoUserPrincipal);
    }

}

From source file:org.apache.jackrabbit.oak.security.authentication.ldap.impl.LdapIdentityProvider.java

@Override
public ExternalUser authenticate(@Nonnull Credentials credentials)
        throws ExternalIdentityException, LoginException {
    if (!(credentials instanceof SimpleCredentials)) {
        log.debug("LDAP IDP can only authenticate SimpleCredentials.");
        return null;
    }/*w  ww.j  av a  2  s  .  c om*/
    final SimpleCredentials creds = (SimpleCredentials) credentials;
    final ExternalUser user = getUser(creds.getUserID());
    if (user != null) {
        // OAK-2078: check for non-empty passwords to avoid anonymous bind on weakly configured servers
        // see http://tools.ietf.org/html/rfc4513#section-5.1.1 for details.
        if (creds.getPassword().length == 0) {
            throw new LoginException(
                    "Refusing to authenticate against LDAP server: Empty passwords not allowed.");
        }

        // authenticate
        LdapConnection connection = null;
        try {
            DebugTimer timer = new DebugTimer();
            if (userPool == null) {
                connection = userConnectionFactory.makeObject();
            } else {
                connection = userPool.getConnection();
            }
            timer.mark("connect");
            connection.bind(user.getExternalId().getId(), new String(creds.getPassword()));
            timer.mark("bind");
            if (log.isDebugEnabled()) {
                log.debug("authenticate({}) {}", user.getId(), timer.getString());
            }
        } catch (LdapAuthenticationException e) {
            throw new LoginException("Unable to authenticate against LDAP server: " + e.getMessage());
        } catch (Exception e) {
            throw new ExternalIdentityException("Error while binding user credentials", e);
        } finally {
            if (connection != null) {
                try {
                    if (userPool == null) {
                        userConnectionFactory.destroyObject(connection);
                    } else {
                        userPool.releaseConnection(connection);
                    }
                } catch (Exception e) {
                    // ignore
                }
            }
        }
    }
    return user;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * attempts to get the users credentials from the users context
 * <p/>//from  w  w w. j  av a2s  . c o m
 * NOTE: this is not an user authenticated operation
 *
 * @param username
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
    String ldapCredential = null;

    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    try {
        Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
        NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments,
                ctls);

        debug("Found user?: " + results.hasMoreElements());

        if (!results.hasMoreElements()) {
            throw new LoginException("User not found.");
        }

        SearchResult result = findUser(username);

        Attributes attributes = result.getAttributes();

        setDemographicAttributes(attributes);
        Attribute attribute = attributes.get(_userPasswordAttribute);
        if (attribute != null) {
            try {
                byte[] value = (byte[]) attribute.get();

                ldapCredential = new String(value);
            } catch (NamingException e) {
                LOG.info("no password available under attribute: " + _userPasswordAttribute);
            }
        }
    } catch (NamingException e) {
        throw new LoginException("Root context binding failure.");
    }

    debug("user cred is present: " + (ldapCredential != null));

    return ldapCredential;
}

From source file:com.streamsets.datacollector.http.LdapLoginModule.java

/**
 * since ldap uses a context bind for valid authentication checking, we override login()
 * <p/>/* w w  w .  j  av a  2  s  .co  m*/
 * if credentials are not available from the users context or if we are forcing the binding check
 * then we try a binding authentication check, otherwise if we have the users encoded password then
 * we can try authentication via that mechanic
 *
 * @return true if authenticated, false otherwise
 * @throws LoginException
 */
@Override
public boolean login() throws LoginException {
    try {
        if (getCallbackHandler() == null) {
            throw new LoginException("No callback handler");
        }
        if (conn == null) {
            return false;
        }

        Callback[] callbacks = configureCallbacks();
        getCallbackHandler().handle(callbacks);

        String webUserName = ((NameCallback) callbacks[0]).getName();
        Object webCredential = ((ObjectCallback) callbacks[1]).getObject();

        if (webUserName == null || webCredential == null) {
            setAuthenticated(false);
            return isAuthenticated();
        }

        // Please see the following stackoverflow article
        // http://security.stackexchange.com/questions/6713/ldap-security-problems
        // Some LDAP implementation "MAY" accept empty password as a sign of anonymous connection and thus
        // return "true" for the authentication request.
        if ((webCredential instanceof String) && ((String) webCredential).isEmpty()) {
            LOG.info("Ignoring login request for user {} as the password is empty.", webUserName);
            setAuthenticated(false);
            return isAuthenticated();
        }
        if (_forceBindingLogin) {
            return bindingLogin(webUserName, webCredential);
        }

        // This sets read and the credential
        UserInfo userInfo = getUserInfo(webUserName);

        if (userInfo == null) {
            setAuthenticated(false);
            return false;
        }

        JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
        jaasUserInfo.fetchRoles();
        setCurrentUser(jaasUserInfo);

        if (webCredential instanceof String) {
            return credentialLogin(Credential.getCredential((String) webCredential));
        }

        return credentialLogin(webCredential);
    } catch (UnsupportedCallbackException e) {
        throw new LoginException("Error obtaining callback information.");
    } catch (IOException e) {
        LOG.error("IO Error performing login", e);
    } catch (Exception e) {
        LOG.error("IO Error performing login", e);
    }
    return false;
}