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.springframework.security.authentication.jaas.DefaultJaasAuthenticationProviderTests.java

License:asdf

@Test
public void logoutLoginException() throws Exception {
    SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
    SecurityContext securityContext = mock(SecurityContext.class);
    JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
    LoginContext context = mock(LoginContext.class);
    LoginException loginException = new LoginException("Failed Login");

    when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
    when(securityContext.getAuthentication()).thenReturn(token);
    when(token.getLoginContext()).thenReturn(context);
    doThrow(loginException).when(context).logout();

    provider.onApplicationEvent(event);//from  w w  w.  j  a va  2  s  .  c om

    verify(event).getSecurityContexts();
    verify(securityContext).getAuthentication();
    verify(token).getLoginContext();
    verify(context).logout();
    verify(log).warn(anyString(), eq(loginException));
    verifyNoMoreInteractions(event, securityContext, token, context);
}

From source file:org.josso.tc60.agent.jaas.SSOGatewayLoginModule.java

/**
 * This method is called if the LoginContext's overall authentication succeeded.
 *
 * Using the SSO user name, saved by the previosuly executed login() operation, obtains from the gateway
 * the roles associated with the user and fills the Subject with the user and role principals.
 * If this LoginModule's own authentication attempted failed, then this method removes any state that was
 * originally saved./*from w  w w. ja  va2  s .  co m*/
 *
 * @exception LoginException if the commit fails.
 *
 * @return true if this LoginModule's own login and commit
 *        attempts succeeded, or false otherwise.
 */
public boolean commit() throws LoginException {
    if (_succeeded == false) {
        return false;
    } else {

        try {

            // Add the SSOUser as a Principal
            if (!_subject.getPrincipals().contains(_ssoUserPrincipal)) {
                _subject.getPrincipals().add(_ssoUserPrincipal);
            }

            logger.debug("Added SSOUser Principal to the Subject : " + _ssoUserPrincipal);

            _ssoRolePrincipals = getRoleSets(_requester);

            // Add to the Subject the SSORoles associated with the SSOUser .
            for (int i = 0; i < _ssoRolePrincipals.length; i++) {
                if (_subject.getPrincipals().contains(_ssoRolePrincipals[i]))
                    continue;

                _subject.getPrincipals().add(_ssoRolePrincipals[i]);
                logger.debug("Added SSORole Principal to the Subject : " + _ssoRolePrincipals[i]);
            }

            commitSucceeded = true;
            return true;
        } catch (Exception e) {
            logger.error("Session login failed for Principal : " + _ssoUserPrincipal, e);
            throw new LoginException("Session login failed for Principal : " + _ssoUserPrincipal);
        } finally {
            // in any case, clean out state
            clearCredentials();
        }

    }
}

From source file:org.hyperic.hq.ui.server.session.DashboardManagerImpl.java

/**
 *//*from  w  w  w  . j  av  a  2s  .  c  om*/
@Transactional(readOnly = true)
public ConfigResponse getRssUserPreferences(String user, String token) throws LoginException {
    ConfigResponse preferences;
    try {
        AuthzSubject me = authzSubjectManager.findSubjectByName(user);
        preferences = getUserDashboard(me, me).getConfig();
    } catch (Exception e) {
        throw new LoginException("Username has no preferences");
    }

    // Let's make sure that the rss auth token matches
    String prefToken = preferences.getValue(Constants.RSS_TOKEN);
    if (token == null || !token.equals(prefToken))
        throw new LoginException("Username and Auth token do not match");

    return preferences;
}

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

/**
 * Execute the rolesQuery against the datasourceName to obtain the roles for
 * the authenticated user.// w ww  .  ja v  a  2s.  c  o  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.nuxeo.ecm.platform.login.NuxeoLoginModule.java

public boolean login() throws LoginException {
    if (manager == null) {
        // throw new LoginException("UserManager implementation not found");
    }// w  w w. j  a  va 2s  .  c  o  m

    loginOk = false;

    identity = getPrincipal();
    if (identity == null) { // auth failed
        throw new LoginException("Authentication Failed");
    }

    if (RestrictedLoginHelper.isRestrictedModeActivated()) {
        if (!identity.isAdministrator()) {
            throw new LoginException("Only Administrators can login when restricted mode is activated");
        }
    }

    loginOk = true;
    log.trace("User '" + identity + "' authenticated");

    /*
     * if( getUseFirstPass() == true ) { // Add the username and password to the shared state map // not sure it's
     * needed sharedState.put("javax.security.auth.login.name", identity.getName());
     * sharedState.put("javax.security.auth.login.password", identity.getPassword()); }
     */

    return true;
}

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

/**
 * This method is called if the LoginContext's overall authentication succeeded.
 *
 * Using the SSO user name, saved by the previosuly executed login() operation, obtains from the gateway
 * the roles associated with the user and fills the Subject with the user and role principals.
 * If this LoginModule's own authentication attempted failed, then this method removes any state that was
 * originally saved./*from   w ww .  j a va  2  s.  co  m*/
 *
 * @exception LoginException if the commit fails.
 *
 * @return true if this LoginModule's own login and commit
 *        attempts succeeded, or false otherwise.
 */
public boolean commit() throws LoginException {
    if (_succeeded == false) {
        return false;
    } else {

        try {

            // Add the SSOUser as a Principal
            if (!_subject.getPrincipals().contains(_ssoUserPrincipal)) {
                _subject.getPrincipals().add(_ssoUserPrincipal);
            }

            if (logger.isDebugEnabled())
                logger.debug("Added SSOUser Principal to the Subject : " + _ssoUserPrincipal);

            _ssoRolePrincipals = getRoleSets();

            // Add to the Subject the SSORoles associated with the SSOUser .
            for (int i = 0; i < _ssoRolePrincipals.length; i++) {
                if (_subject.getPrincipals().contains(_ssoRolePrincipals[i]))
                    continue;

                _subject.getPrincipals().add(_ssoRolePrincipals[i]);
                if (logger.isDebugEnabled())
                    logger.debug("Added SSORole Principal to the Subject : " + _ssoRolePrincipals[i]);
            }

            commitSucceeded = true;
            return true;

        } catch (Exception e) {
            logger.error("Session commit failed for Principal : " + _ssoUserPrincipal + e.getMessage());
            // Only log if debug is enabled ...
            if (logger.isDebugEnabled())
                logger.debug(e.getMessage(), e);

            throw new LoginException(
                    "Session commit failed for Principal : " + _ssoUserPrincipal + " : " + e.getMessage());
        } finally {
            // in any case, clean out state
            clearCredentials();
        }

    }
}

From source file:org.transdroid.search.hdbitsorg.HdBitsOrgAdapter.java

/**
 * Attempts to log in to hdbits.org with the given credentials. On success
 * the given DefaultHttpClient should hold all required cookies to access
 * the site./*  www . ja v  a  2  s  . com*/
 */
private void login(DefaultHttpClient client, String username, String password, String token) throws Exception {
    Log.d(LOG_TAG, "Attempting to login.");

    HttpPost request = new HttpPost(LOGIN_URL);
    request.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair[] {
            new BasicNameValuePair(LOGIN_POST_USERNAME, username),
            new BasicNameValuePair(LOGIN_POST_PASSWORD, password),
            new BasicNameValuePair(LOGIN_POST_TOKEN, token), new BasicNameValuePair("returnto", "%2F") })));

    client.execute(request);

    // verify we have the cookies needed to log in
    boolean success = false, uid = false, pass = false, hash = false;
    for (Cookie cookie : client.getCookieStore().getCookies()) {
        if ("uid".equals(cookie.getName()))
            uid = true;
        if ("pass".equals(cookie.getName()))
            pass = true;
        if ("hash".equals(cookie.getName()))
            hash = true;
    }

    // if we don't have the correct cookies, login failed. notify user with a toast and toss an exception.
    success = uid && pass && hash;
    if (!success) {
        Log.e(LOG_TAG,
                "Failed to log into hdbits.org as '" + username + "'. Did not receive expected login cookies!");
        throw new LoginException(
                "Failed to log into hdbits.org as '" + username + "'. Did not receive expected login cookies!");
    }

    Log.d(LOG_TAG, "Successfully logged in to hdbits.org.");
}

From source file:com.ideabase.repository.core.auth.RepositoryLoginModule.java

/**
 * remove user principal from subject and clean out the states.
 * <br>// w  w  w . jav a 2s .  co  m
 * {@inheritDoc}
 */
public boolean logout() throws LoginException {
    if (mSubject.isReadOnly()) {
        throw new LoginException("Subject is read-only");
    }
    mSubject.getPrincipals().remove(mUser);

    // clean out state
    mSucceeded = false;
    mCommitSucceeded = false;
    mUser = null;

    LOG.debug("logout - Subject is being logged out");

    return true;
}

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

/**
 * This method is called if the LoginContext's overall authentication succeeded.
 *
 * Using the SSO user name, saved by the previosuly executed login() operation, obtains from the gateway
 * the roles associated with the user and fills the Subject with the user and role principals.
 * If this LoginModule's own authentication attempted failed, then this method removes any state that was
 * originally saved./*  ww  w.j  a  va2 s . c o m*/
 *
 * @exception javax.security.auth.login.LoginException if the commit fails.
 *
 * @return true if this LoginModule's own login and commit
 *        attempts succeeded, or false otherwise.
 */
public boolean commit() throws LoginException {
    if (_succeeded == false) {
        return false;
    } else {

        try {

            // Add the SSOUser as a Principal
            if (!_subject.getPrincipals().contains(_ssoUserPrincipal)) {
                _subject.getPrincipals().add(_ssoUserPrincipal);
            }

            if (logger.isDebugEnabled())
                logger.debug("Added SSOUser Principal to the Subject : " + _ssoUserPrincipal);

            _ssoRolePrincipals = getRoleSets();

            // Add to the Subject the SSORoles associated with the SSOUser .
            for (int i = 0; i < _ssoRolePrincipals.length; i++) {
                if (_subject.getPrincipals().contains(_ssoRolePrincipals[i]))
                    continue;

                _subject.getPrincipals().add(_ssoRolePrincipals[i]);

                if (logger.isDebugEnabled())
                    logger.debug("Added SSORole Principal to the Subject : " + _ssoRolePrincipals[i]);
            }

            commitSucceeded = true;
            return true;

        } catch (Exception e) {
            logger.error("Session commit failed for Principal : " + _ssoUserPrincipal + e.getMessage());
            // Only log if debug is enabled ...
            if (logger.isDebugEnabled())
                logger.debug(e.getMessage(), e);

            throw new LoginException(
                    "Session commit failed for Principal : " + _ssoUserPrincipal + " : " + e.getMessage());
        } finally {
            // in any case, clean out state
            clearCredentials();
        }

    }
}

From source file:gov.nih.nci.security.authentication.loginmodules.CSMLoginModule.java

/**
 * Retrieves the user credentials from the CallBacks and tries to validate 
 * them against the database. It retrieves userID and password from the 
 * CallbackHandler. It uses helper class to perform the actual authentication 
 * operations and access the user record. This method returns a true if
 * the user authentication was sucessful else it throws a Login Exception.
 * @throws LoginException /*ww  w .j a  v a2  s .c  o  m*/
 * @see javax.security.auth.spi.LoginModule#login()
 */
public boolean login() throws LoginException, CSInternalLoginException, CSInternalConfigurationException {
    if (callbackHandler == null) {
        if (log.isDebugEnabled())
            log.debug("Authentication|||login|Failure| Error in obtaining the CallBack Handler |");
        throw new LoginException("Error in obtaining Callback Handler");
    }
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("userid: ");
    callbacks[1] = new PasswordCallback("password: ", false);

    try {
        callbackHandler.handle(callbacks);
        userID = ((NameCallback) callbacks[0]).getName();
        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();

        if (tmpPassword == null) {
            // treat a NULL password as an empty password
            tmpPassword = new char[0];
        }
        password = new char[tmpPassword.length];
        System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
        ((PasswordCallback) callbacks[1]).clearPassword();
    } catch (java.io.IOException e) {
        if (log.isDebugEnabled())
            log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |"
                    + e.getMessage());
        throw new LoginException("Error in Creating the CallBack Handler");
    } catch (UnsupportedCallbackException e) {
        if (log.isDebugEnabled())
            log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |"
                    + e.getMessage());
        throw new LoginException("Error in Creating the CallBack Handler");
    }
    if (isFirstTimeLogin(options, userID)) {
        loginSuccessful = false;
        password = null;
        throw new FailedLoginException("User logging in first time, Password should be changed ");
    }
    DataConfiguration config;
    try {
        config = ConfigurationHelper.getConfiguration();
    } catch (CSConfigurationException e) {
        // TODO Auto-generated catch block
        throw new CSInternalConfigurationException("Exception while reading config data!!");
    }

    if (isPasswordExpired(options, userID)) {
        loginSuccessful = false;
        userID = null;
        password = null;

        throw new CredentialExpiredException("User password expired, Ceate new password");
    }

    try {
        //now validate user
        if (validate(options, userID, password, subject)) {
            if (isActive(options, userID))
                loginSuccessful = true;
            else {
                loginSuccessful = false;
                password = null;
                throw new AccountExpiredException("User is not active, Contact the system administrator");
            }
        } else {
            // clear the values         
            loginSuccessful = false;
            userID = null;
            password = null;

            throw new LoginException("Invalid Login Credentials");
        }
    } catch (FailedLoginException fle) {
        if (log.isDebugEnabled())
            if (log.isDebugEnabled())
                log.debug("Authentication|||login|Failure| Invalid Login Credentials |" + fle.getMessage());
        throw new LoginException("Invalid Login Credentials");
    }
    if (log.isDebugEnabled())
        log.debug("Authentication|||login|Success| Authentication is " + loginSuccessful + "|");
    return loginSuccessful;
}