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:com.ibm.tivoli.tuna.jaas.ldap.LdapLoginModule.java

/**
 * Authenticate the user by prompting for a user name and password.
 * /* w  ww .  j a  va 2 s .  c o m*/
 * <p>
 * 
 * @return true in all cases since this <code>LoginModule</code> should not be
 *         ignored.
 * 
 * @exception FailedLoginException
 *              if the authentication fails.
 *              <p>
 * 
 * @exception LoginException
 *              if this <code>LoginModule</code> is unable to perform the
 *              authentication.
 */
public boolean login() throws LoginException {

    // prompt for a user name and password
    if (callbackHandler == null)
        throw new LoginException(
                "Error: no CallbackHandler available " + "to garner authentication information from the user");

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("user name: ");
    callbacks[1] = new PasswordCallback("password: ", false);

    try {
        callbackHandler.handle(callbacks);
        username = ((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 ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("Error: " + uce.getCallback().toString()
                + " not available to garner authentication information " + "from the user");
    }

    // print debugging information
    log.debug("\t\t[LdapLoginModule] " + "user entered user name: " + username);
    log.debug("\t\t[LdapLoginModule] " + "user entered password: ");

    // verify the username/password
    //LdapServiceDao ldapService = new LdapServiceDao();
    boolean usernameCorrect = false;
    try {
        ILdapUserDao ldapService = (ILdapUserDao) this.applicationContext.getBean(this.ldapDaoBeanName);

        String userDn = ldapService.searchUserDNByAccount(username);
        if (!StringUtil.isNull(userDn)) {
            usernameCorrect = true;

            //??
            ldapService.authenticateUser(userDn, password);

            UserDNPrincipal userDNPrincipal = new UserDNPrincipal(userDn);
            if (!subject.getPrincipals().contains(userDNPrincipal))
                subject.getPrincipals().add(userDNPrincipal);

            log.debug("\t\t[LdapLoginModule] " + "authentication succeeded");
        }

        if (!usernameCorrect) {
            log.debug("\t\t[LdapLoginModule] " + "authentication failed");
            succeeded = false;
            username = null;
            for (int i = 0; i < password.length; i++)
                password[i] = ' ';
            password = null;
            throw new FailedLoginException("UserName Incorrect");
        } else {
            succeeded = true;
            return true;
        }

    } catch (EmptyResultDataAccessException e) {
        succeeded = false;
        throw new FailedLoginException("user isnot found");
    } catch (IncorrectResultSizeDataAccessException e) {
        succeeded = false;
        throw new FailedLoginException("user found multi");
    } catch (Exception e) {
        succeeded = false;
        throw new FailedLoginException("password is wrong");
    }

}

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

/**
 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#login()
 *///from   w  w w .ja  v a2s . c  o m
@Override
public boolean login() throws LoginException {
    try {
        HttpServletRequest request = getCurrentRequest();
        String authorization = request.getHeader("Authorization"); //$NON-NLS-1$
        if (authorization != null && authorization.startsWith("Basic")) { //$NON-NLS-1$
            String b64Data = authorization.substring(6);
            byte[] dataBytes = Base64.decodeBase64(b64Data);
            String data = new String(dataBytes, "UTF-8"); //$NON-NLS-1$
            if (data.startsWith("SAML-BEARER-TOKEN:")) { //$NON-NLS-1$
                String assertionData = data.substring(18);
                Document samlAssertion = DocumentUtil.getDocument(assertionData);
                SAMLAssertionParser parser = new SAMLAssertionParser();
                DOMSource source = new DOMSource(samlAssertion);
                XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(source);
                Object parsed = parser.parse(xmlEventReader);
                AssertionType assertion = (AssertionType) parsed;
                SAMLBearerTokenUtil.validateAssertion(assertion, request, allowedIssuers);
                if ("true".equals(signatureRequired)) { //$NON-NLS-1$
                    KeyPair keyPair = getKeyPair(assertion);
                    if (!SAMLBearerTokenUtil.isSAMLAssertionSignatureValid(samlAssertion, keyPair)) {
                        throw new LoginException(
                                Messages.getString("SAMLBearerTokenLoginModule.InvalidSignature")); //$NON-NLS-1$
                    }
                }
                consumeAssertion(assertion);
                loginOk = true;
                return true;
            }
        }
    } catch (LoginException le) {
        throw le;
    } catch (Exception e) {
        e.printStackTrace();
        loginOk = false;
        return false;
    }
    return super.login();
}

From source file:net.ontopia.topicmaps.nav2.realm.TMLoginModule.java

/** 
 * Prompt the user for username and password, and verify those.
 *///from   w  w w  . jav  a 2s.  co  m
@Override
public boolean login() throws LoginException {
    log.debug("TMLoginModule: login");

    if (callbackHandler == null)
        throw new LoginException(
                "Error: no CallbackHandler available " + "to garner authentication information from the user");

    // prompt for a user name and password
    NameCallback nameCallback = new NameCallback("user name: ");
    PasswordCallback passwordCallback = new PasswordCallback("password: ", false);

    try {
        callbackHandler.handle(new Callback[] { nameCallback, passwordCallback });

        this.username = nameCallback.getName();
        char[] charpassword = passwordCallback.getPassword();
        password = (charpassword == null ? "" : new String(charpassword));
        passwordCallback.clearPassword();

    } catch (java.io.IOException ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("Error: " + uce.getCallback()
                + " not available to garner authentication information " + "from the user");
    }
    // verify the username/password
    loginSucceeded = verifyUsernamePassword(username, password);
    return loginSucceeded;
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.jboss.DBLoginModule.java

protected String[] getUsernameAndPassword() throws LoginException {
    String[] info = { null, null };
    if (callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available to collect authentication information");
    }// w  ww.  j  av  a 2 s . c  o m
    NameCallback nc = new NameCallback("User name: ", "guest");
    PasswordCallback pc = new PasswordCallback("Password: ", false);
    Callback[] callbacks = { nc, pc };
    String username = null;
    String password = null;
    try {
        callbackHandler.handle(callbacks);
        username = nc.getName();
        char[] tmpPassword = pc.getPassword();
        if (tmpPassword != null) {
            credential = new char[tmpPassword.length];
            System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
            pc.clearPassword();
            password = new String(credential);
        }
    } catch (IOException ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("CallbackHandler does not support: " + uce.getCallback());
    }
    info[0] = username;
    info[1] = password;
    logger.debug("Username=" + username);
    return info;
}

From source file:info.magnolia.jaas.sp.AbstractLoginModule.java

@Override
public boolean login() throws LoginException {
    if (this.getSkip()) {
        return true;
    }/*from w  w w.j  a  va2 s.  com*/

    if (this.callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("name");
    callbacks[1] = new PasswordCallback("pswd", false);

    // if the realm is not defined in the jaas configuration
    // we ask use a callback to get the value
    if (this.useRealmCallback) {
        callbacks = (Callback[]) ArrayUtils.add(callbacks, new RealmCallback());
    }

    this.success = false;
    try {
        this.callbackHandler.handle(callbacks);
        this.name = ((NameCallback) callbacks[0]).getName();
        this.pswd = ((PasswordCallback) callbacks[1]).getPassword();
        if (this.useRealmCallback) {
            String aRealm = ((RealmCallback) callbacks[2]).getRealm();
            this.realm = StringUtils.isBlank(aRealm) ? this.realm : Realm.Factory.newRealm(aRealm);
        }

        this.validateUser();
    } catch (IOException ioe) {
        log.debug("Exception caught", ioe);
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException ce) {
        log.debug(ce.getMessage(), ce);
        throw new LoginException(ce.getCallback().toString() + " not available");
    }

    // TODO: should not we set success BEFORE calling validateUser to give it chance to decide whether to throw an exception or reset the value to false?
    this.success = true;
    this.setSharedStatus(STATUS_SUCCEEDED);
    return this.success;
}

From source file:com.docdoku.cli.helpers.FileHelper.java

private void manageHTTPCode(HttpURLConnection conn) throws IOException, LoginException {
    int code = conn.getResponseCode();
    switch (code) {
    case 401:/*from ww  w  .  j  a  va2 s  . c  o m*/
    case 403:
        throw new LoginException("Error trying to login");
    case 500:
        throw new IOException(conn.getHeaderField("Reason-Phrase"));
    }
}

From source file:org.apache.hive.service.auth.HiveAuthFactory.java

public TTransportFactory getAuthTransFactory() throws LoginException {
    TTransportFactory transportFactory;//w  w w  .  j a  va  2s .  c  o  m
    TSaslServerTransport.Factory serverTransportFactory;

    if (isSASLWithKerberizedHadoop()) {
        try {
            serverTransportFactory = saslServer.createSaslServerTransportFactory(getSaslProperties());
        } catch (TTransportException e) {
            throw new LoginException(e.getMessage());
        }
        if (authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.KERBEROS.getAuthName())) {
            // no-op
        } else if (authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.NONE.getAuthName())
                || authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.LDAP.getAuthName())
                || authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.PAM.getAuthName())
                || authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.CUSTOM.getAuthName())) {
            try {
                serverTransportFactory.addServerDefinition("PLAIN", authTypeStr, null,
                        new HashMap<String, String>(),
                        new PlainSaslHelper.PlainServerCallbackHandler(authTypeStr));
            } catch (AuthenticationException e) {
                throw new LoginException("Error setting callback handler" + e);
            }
        } else {
            throw new LoginException("Unsupported authentication type " + authTypeStr);
        }
        transportFactory = saslServer.wrapTransportFactory(serverTransportFactory);
    } else if (authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.NONE.getAuthName())
            || authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.LDAP.getAuthName())
            || authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.PAM.getAuthName())
            || authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.CUSTOM.getAuthName())) {
        transportFactory = PlainSaslHelper.getPlainTransportFactory(authTypeStr);
    } else if (authTypeStr.equalsIgnoreCase(HiveAuthConstants.AuthTypes.NOSASL.getAuthName())) {
        transportFactory = new TTransportFactory();
    } else {
        throw new LoginException("Unsupported authentication type " + authTypeStr);
    }
    return transportFactory;
}

From source file:org.polymap.core.security.DummyLoginModule.java

public boolean login() throws LoginException {
    // check if there is a user with "login" password
    for (DummyUserPrincipal candidate : users.values()) {
        if (candidate.getPassword().equals("login")) {
            principal = candidate;/*ww w  .  ja  va  2s.c o  m*/
            return loggedIn = true;
        }
    }

    try {
        Callback label = new TextOutputCallback(TextOutputCallback.INFORMATION,
                // empty if service login
                StringUtils.defaultIfEmpty(dialogTitle, "POLYMAP3 Workbench"));
        NameCallback nameCallback = new NameCallback(
                StringUtils.defaultIfEmpty(i18n.get("username"), "Username"), "default");
        PasswordCallback passwordCallback = new PasswordCallback(
                StringUtils.defaultIfEmpty(i18n.get("password"), "Password"), false);

        callbackHandler.handle(new Callback[] { label, nameCallback, passwordCallback });

        String username = nameCallback.getName();

        String password = "";
        if (passwordCallback.getPassword() != null) {
            password = String.valueOf(passwordCallback.getPassword());
        }

        DummyUserPrincipal candidate = userForName(username);
        if (candidate.getPassword().equals(password)) {
            principal = candidate;
            loggedIn = true;
            return true;
        }
        return false;
    } catch (Exception e) {
        log.warn("", e);
        throw new LoginException(e.getLocalizedMessage());
    }
}

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

/**
 * Perform Lucene index search by user name and user password. <br>
 * if indexer returns some value. it means the requset is from valid user.<br>
 * send another callback request, this callback request pack the user id.<br>
 * the callback handler can retrieve user object from storage.<br>
 * create new {@see RepositoryUserPrincipal}. <br>
 *//*from  ww  w. j  a v a 2  s. c om*/
private void authenticateUser(final String pUserName, final String pUserPassword)
        throws LoginException, IOException, UnsupportedCallbackException {

    final String userHashKey = DigestUtils.shaHex(pUserName + pUserPassword);
    final User user = API.giveMe().repositoryService().getItemByTitle(userHashKey, User.class);
    if (user != null) {
        final Integer userId = user.getId();
        // send other callback request with user id.
        Callback[] callbacks = new Callback[1];
        callbacks[0] = new TextOutputCallback(TextOutputCallback.INFORMATION, String.valueOf(userId));
        mCallbackHandler.handle(callbacks);

        if (DEBUG) {
            LOG.debug("Search result id - " + userId);
        }

        // create repository user principal
        if (!user.isAdmin()) {
            mUser = new RepositoryUserPrincipal(PRINCIPAL_USER, userId);
        } else {
            mUser = new RepositoryUserPrincipal(PRINCIPAL_ADMIN, userId);
        }
    } else {
        throw new LoginException("Login failed. Invalid user or password.");
    }
}

From source file:com.zimbra.cs.datasource.imap.ConnectionManager.java

public static ImapConnection newConnection(DataSource ds, Authenticator auth) throws ServiceException {
    ImapConfig config = newImapConfig(ds);
    ImapConnection ic = new ImapConnection(config);
    ic.setDataHandler(new FetchDataHandler());
    try {/*from  w w  w  .  j  a  v  a 2 s .c  om*/
        ic.connect();
        try {
            if (config.getMechanism() != null) {
                if (SaslAuthenticator.XOAUTH2.equalsIgnoreCase(config.getMechanism())) {
                    auth = AuthenticatorFactory.getDefault().newAuthenticator(config,
                            ds.getDecryptedOAuthToken());
                } else {
                    auth = AuthenticatorFactory.getDefault().newAuthenticator(config,
                            ds.getDecryptedPassword());
                }
            }
            if (auth == null) {
                ic.login(ds.getDecryptedPassword());
            } else {
                ic.authenticate(auth);
            }
        } catch (CommandFailedException e) {
            if (SaslAuthenticator.XOAUTH2.equalsIgnoreCase(config.getMechanism())) {
                try {
                    DataSourceManager.refreshOAuthToken(ds);
                    config.getSaslProperties().put(
                            "mail." + config.getProtocol() + ".sasl.mechanisms.oauth2.oauthToken",
                            ds.getDecryptedOAuthToken());
                    auth = AuthenticatorFactory.getDefault().newAuthenticator(config,
                            ds.getDecryptedOAuthToken());
                    ic.authenticate(auth);
                } catch (CommandFailedException e1) {
                    ZimbraLog.datasource.warn("Exception in connecting to data source", e);
                    throw new LoginException(e1.getError());
                }
            } else {
                throw new LoginException(e.getError());
            }
        }
        if (isImportingSelf(ds, ic)) {
            throw ServiceException.INVALID_REQUEST("User attempted to import messages from his/her own mailbox",
                    null);
        }
    } catch (ServiceException e) {
        ic.close();
        throw e;
    } catch (Exception e) {
        ic.close();
        throw ServiceException.FAILURE("Unable to connect to IMAP server: " + ds, e);
    }
    LOG.debug("Created new connection: " + ic);
    return ic;
}