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.polymap.core.runtime.Polymap.java

/**
 * Logging in using default JAAS config.
 *//*from   w ww .j a v a 2  s  . co  m*/
public void login() {
    HttpServletRequest request = RWT.getRequest();
    initHttpParams = new HashMap(request.getParameterMap());

    String jaasConfigFile = "jaas_config.txt";
    File configFile = new File(getWorkspacePath().toFile(), jaasConfigFile);

    // create default config
    if (!configFile.exists()) {
        FileOutputStream out = null;
        try {
            log.info("Creating default JAAS config: " + configFile.getAbsolutePath());
            URL defaultConfigUrl = CorePlugin.getDefault().getBundle().getEntry(jaasConfigFile);
            out = new FileOutputStream(configFile);
            IOUtils.copy(defaultConfigUrl.openStream(), out);
        } catch (Exception e) {
            throw new RuntimeException("Unable to create default jaas_config.txt in workspace.", e);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    // create secureContext
    try {
        secureContext = LoginContextFactory.createContext(DEFAULT_LOGIN_CONFIG, configFile.toURI().toURL());
    } catch (MalformedURLException e) {
        throw new RuntimeException("Should never happen.", e);
    }

    // login
    for (boolean loggedIn = false; !loggedIn;) {
        try {
            secureContext.login();

            subject = secureContext.getSubject();
            principals = new HashSet(subject.getPrincipals());

            // find user
            for (Principal principal : principals) {
                if (principal instanceof UserPrincipal) {
                    user = (UserPrincipal) principal;
                    break;
                }
            }
            if (user == null) {
                throw new LoginException("Es wurde kein Nutzer in der Konfiguration gefunden");
            }

            // allow to access the instance directly via current session (find user for example)
            SessionContext.current().setAttribute("user", user);

            // add roles of user to principals
            Set<AuthorizationModule> authModules = subject.getPrivateCredentials(AuthorizationModule.class);
            if (authModules.size() != 1) {
                throw new RuntimeException("No AuthorizationModule specified. Is jaas_config.txt correct?");
            }
            principals.addAll(authModules.iterator().next().rolesOf(subject));

            loggedIn = true;
        } catch (LoginException e) {
            log.warn("Login error: " + e.getLocalizedMessage(), e);
            //                // FIXME causes zombie threads?
            //                // XXX translation
            //                IStatus status = new Status( IStatus.ERROR, CorePlugin.PLUGIN_ID, "Login fehlgeschlagen.", e );
            //                ErrorDialog.openError( null, "Achtung", "Login fehlgeschlagen", status );
        }
    }
}

From source file:org.nuxeo.ecm.platform.login.test.DummyNuxeoLoginModule.java

@SuppressWarnings({ "unchecked" })
protected NuxeoPrincipal getPrincipal() throws LoginException {
    UserIdentificationInfo userIdent = null;

    // **** init the callbacks
    // Std login/password callbacks
    NameCallback nc = new NameCallback("Username: ", SecurityConstants.ANONYMOUS);
    PasswordCallback pc = new PasswordCallback("Password: ", false);

    // Nuxeo specific cb : handle LoginPlugin initialization
    UserIdentificationInfoCallback uic = new UserIdentificationInfoCallback();

    // JBoss specific cb : handle web=>ejb propagation
    // SecurityAssociationCallback ac = new SecurityAssociationCallback();
    // ObjectCallback oc = new ObjectCallback("UserInfo:");

    // **** handle callbacks
    // We can't check the callback handler class to know what will be
    // supported//  ww w .ja  va2 s.c  om
    // because the cbh is wrapped by JAAS
    // => just try and swalow exceptions
    // => will be externalised to plugins via EP to avoid JBoss dependency
    boolean cb_handled = false;

    try {
        // only try this cbh when called from the web layer
        if (useUserIdentificationInfoCB) {
            callbackHandler.handle(new Callback[] { uic });
            // First check UserInfo CB return
            userIdent = uic.getUserInfo();
            cb_handled = true;
        }
    } catch (UnsupportedCallbackException e) {
        log.debug("UserIdentificationInfoCallback is not supported");
    } catch (IOException e) {
        log.warn("Error calling callback handler with UserIdentificationInfoCallback : " + e.getMessage());
    }

    Principal principal = null;
    Object credential = null;

    if (!cb_handled) {
        CallbackResult result = loginPluginManager.handleSpecifcCallbacks(callbackHandler);

        if (result != null && result.cb_handled) {
            if (result.userIdent != null && result.userIdent.containsValidIdentity()) {
                userIdent = result.userIdent;
                cb_handled = true;
            } else {
                principal = result.principal;
                credential = result.credential;
                if (principal != null) {
                    cb_handled = true;
                }
            }
        }
    }

    if (!cb_handled) {
        try {
            // Std CBH : will only works for L/P
            callbackHandler.handle(new Callback[] { nc, pc });
            cb_handled = true;
        } catch (UnsupportedCallbackException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        } catch (IOException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        }
    }

    try {
        // Login via the Web Interface : may be using a plugin
        if (userIdent != null && userIdent.containsValidIdentity()) {
            NuxeoPrincipal nxp = validateUserIdentity(userIdent);

            if (nxp != null) {
                sharedState.put("javax.security.auth.login.name", nxp.getName());
                sharedState.put("javax.security.auth.login.password", userIdent);
            }
            return nxp;
        }

        if (LoginComponent.isSystemLogin(principal)) {
            return new SystemPrincipal(principal.getName());
        }

        if (principal != null) { // a non null principal
            String password = null;
            if (credential instanceof char[]) {
                password = new String((char[]) credential);
            } else if (credential != null) {
                password = credential.toString();
            }
            return validateUsernamePassword(principal.getName(), password);
        } else { // we don't have a principal - try the username &
            // password
            String username = nc.getName();
            if (username == null) {
                return null;
            }
            char[] password = pc.getPassword();
            return validateUsernamePassword(username, password != null ? new String(password) : null);
        }
    } catch (LoginException e) {
        throw e;
    } catch (Exception e) {
        // jboss catches LoginException, so show it at least in the logs
        String msg = "Authentication failed: " + e.getMessage();
        log.error(msg, e);
        throw (LoginException) new LoginException(msg).initCause(e);
    }
}

From source file:org.overlord.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * Gets the key pair to use to validate the assertion's signature.  The key pair is retrieved
 * from the keystore./*from   www.  ja v a  2s . co  m*/
 * @param assertion
 * @throws LoginException
 */
private KeyPair getKeyPair(AssertionType assertion) throws LoginException {
    KeyStore keystore = loadKeystore();
    try {
        return SAMLBearerTokenUtil.getKeyPair(keystore, keyAlias, keyPassword);
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException(
                Messages.getString("SAMLBearerTokenLoginModule.FailedToGetKeyPair") + keyAlias); //$NON-NLS-1$
    }
}

From source file:org.jboss.datavirt.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * Loads the keystore./*  w  w w  . j  a  v a 2  s .c  om*/
 * @throws LoginException
 */
private KeyStore loadKeystore() throws LoginException {
    try {
        return SAMLBearerTokenUtil.loadKeystore(keystorePath, keystorePassword);
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException("Error loading signature keystore: " + e.getMessage());
    }
}

From source file:org.transdroid.search.hdtorrents.HdTorrentsAdapter.java

/**
 * Attempts to log in to HD-Torrents.org with the given credentials. On success
 * the given DefaultHttpClient should hold all required cookies to access
 * the site.//from w  w w  .j a v a  2 s.com
 */
private void login(DefaultHttpClient client, String username, String password) 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) })));

    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 ("hashx".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 HD-Torrents as '" + username
                + "'. Did not receive expected login cookies!");
        throw new LoginException("Failed to log into HD-Torrents as '" + username
                + "'. Did not receive expected login cookies!");
    }

    Log.d(LOG_TAG, "Successfully logged in to HD-Torrents");
}

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

/**
 * if login not succeeded return false.<br>
 * else if subject is set to readonly throw exception.<br>
 * if subject pricipal doesn't contain user. add new
 * {@see RepositoryUserPricipal}. <br>
 * set {@code mCommitSucceeded} state = true
 * <br>//from w  w w  .j  av a  2  s  .c  o m
 * {@inheritDoc}
 */
public boolean commit() throws LoginException {
    LOG.debug("Commit action is triggered.");
    if (!mSucceeded) {
        return false;
    } else {
        if (mSubject.isReadOnly()) {
            throw new LoginException("Subject is read-only");
        }
        // add Principals to the Subject
        if (!mSubject.getPrincipals().contains(mUser)) {
            mSubject.getPrincipals().add(mUser);
        }

        LOG.debug("commit - Authentication has completed successfully");
    }
    mCommitSucceeded = true;
    return true;
}

From source file:org.josso.gl2.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  .j  a  v a2s .  c  om*/
 *
 * @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();

            // 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.josso.jaspi.agent.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.// www .j  ava 2  s .c  o 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();

            // 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.overlord.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * Loads the keystore.// w  w w .j a  v  a 2  s.co m
 * @throws LoginException
 */
private KeyStore loadKeystore() throws LoginException {
    try {
        return SAMLBearerTokenUtil.loadKeystore(keystorePath, keystorePassword);
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException("Error loading signature keystore: " + e.getMessage()); //$NON-NLS-1$
    }
}

From source file:org.josso.wls81.agent.mbeans.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 w w .java2 s .  c o  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();

            // 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 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();
        }

    }
}