Example usage for javax.security.auth.callback PasswordCallback getPassword

List of usage examples for javax.security.auth.callback PasswordCallback getPassword

Introduction

In this page you can find the example usage for javax.security.auth.callback PasswordCallback getPassword.

Prototype

public char[] getPassword() 

Source Link

Document

Get the retrieved password.

Usage

From source file:org.opensc.pkcs11.PKCS11SessionStore.java

/**
 * This method allows you to authenticate you against the token, if the initial call to
 * {@link #open(LoadStoreParameter)} did not contain a
 * ProtectionParameter. This may be use in order to search for a certificate on a token
 * without entering a PIN./*w w w  .j a  v  a  2  s .  com*/
 * 
 * @param param The protection parameters used to do normal (user) authentication.
 * 
 * @see PKCS11LoadStoreParameter#getProtectionParameter()
 */
public void authenticate(ProtectionParameter param) throws IOException {
    this.protectionParameter = param;

    try {
        if (this.protectionParameter instanceof PasswordProtection) {
            changeEvent(PKCS11EventCallback.PIN_AUTHENTICATION_IN_PROGRESS);
            PasswordProtection pp = (PasswordProtection) this.protectionParameter;

            this.session.loginUser(pp.getPassword());
            changeEvent(PKCS11EventCallback.AUHENTICATION_SUCEEDED);
        } else if (this.protectionParameter instanceof CallbackHandlerProtection) {
            CallbackHandlerProtection cbhp = (CallbackHandlerProtection) this.protectionParameter;

            char[] pin = null;
            // do authenticate with the protected auth method of the token,
            // if this is possible, otherwise use the callback to authenticate. 
            if (this.slot.hasTokenProtectedAuthPath()) {
                changeEvent(PKCS11EventCallback.HW_AUTHENTICATION_IN_PROGRESS);
            } else {
                changeEvent(PKCS11EventCallback.WAITING_FOR_SW_PIN);

                CallbackHandler cbh = cbhp.getCallbackHandler();

                PasswordCallback pcb = new PasswordCallback("Please enter the user pin:", false);
                cbh.handle(new Callback[] { pcb });

                pin = pcb.getPassword();
                changeEvent(PKCS11EventCallback.PIN_AUTHENTICATION_IN_PROGRESS);
            }

            this.session.loginUser(pin);
            changeEvent(PKCS11EventCallback.AUHENTICATION_SUCEEDED);
        }
    } catch (UnsupportedCallbackException e) {
        throw new PKCS11Exception("PasswordCallback is not supported", e);
    }
}

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;/*from   w  w  w  .ja  v a 2  s.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:net.ontopia.topicmaps.nav2.realm.TMLoginModule.java

/** 
 * Prompt the user for username and password, and verify those.
 *///  w w  w .  ja  v a  2 s. com
@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:edu.vt.middleware.ldap.jaas.AbstractLoginModule.java

/**
 * This will store the supplied name, password, and entry dn in the stored
 * state map. storePass must be set for this method to have any affect.
 *
 * @param  nameCb  to store//from w  w w.  j ava  2  s.c  o  m
 * @param  passCb  to store
 * @param  loginDn  to store
 */
@SuppressWarnings("unchecked")
protected void storeCredentials(final NameCallback nameCb, final PasswordCallback passCb,
        final String loginDn) {
    if (this.storePass) {
        if (nameCb != null && nameCb.getName() != null) {
            this.sharedState.put(LOGIN_NAME, nameCb.getName());
        }
        if (passCb != null && passCb.getPassword() != null) {
            this.sharedState.put(LOGIN_PASSWORD, passCb.getPassword());
        }
        if (loginDn != null) {
            this.sharedState.put(LOGIN_DN, loginDn);
        }
    }
}

From source file:org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabaseTest.java

/** **** Test Methods ************** */

public void testCreatePrincipal() {
    File testFile = createPasswordFile(1, 0);

    loadPasswordFile(testFile);/*w  w  w  .j  a v a  2  s. c o  m*/

    Principal principal = new Principal() {
        public String getName() {
            return USERNAME;
        }
    };

    assertTrue("New user not created.", _database.createPrincipal(principal, PASSWORD.toCharArray()));

    PasswordCallback callback = new PasswordCallback("prompt", false);
    try {
        _database.setPassword(principal, callback);
    } catch (AccountNotFoundException e) {
        fail("user account did not exist");
    }
    assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword()));

    loadPasswordFile(testFile);

    try {
        _database.setPassword(principal, callback);
    } catch (AccountNotFoundException e) {
        fail("user account did not exist");
    }
    assertTrue("Password returned was incorrect.", Arrays.equals(PASSWORD_MD5_CHARS, callback.getPassword()));

    assertNotNull("Created User was not saved", _database.getUser(USERNAME));

    assertFalse("Duplicate user created.", _database.createPrincipal(principal, PASSWORD.toCharArray()));
}

From source file:org.getobjects.jaas.GoDefaultLoginModule.java

/**
 * This is the default JAAS Phase 1 implementation, which grabs login/pwd
 * from the CallbackHandler (eg the one provided by the GoHTTPAuthenticator)
 * and calls loginWithUsernameAndPassword() with this information.
 * //  ww w .  j a  v a 2  s  .co m
 * @return true if authentication was successful, false otherwise
 * @throws LoginException
 */
protected boolean loginWithUsernameAndPassword() throws LoginException {
    /* first retrieve username/password */

    NameCallback nc = new NameCallback("login");
    PasswordCallback pc = new PasswordCallback("password", false /* no echo */);

    try {
        this.handler.handle(new Callback[] { nc, pc });
    } catch (IOException ie) {
        log.error("some IO error occurred during Name/PasswordCallback retrieval", ie);
        return false;
    } catch (UnsupportedCallbackException uce) {
        /* token callbacks unsupported, this is OK */
        return false;
    }

    /* then attempt a login */

    return this.loginWithUsernameAndPassword(nc.getName(), pc.getPassword());
}

From source file:net.sf.jpam.jaas.JpamLoginModule.java

/**
 * Method to authenticate a <code>Subject</code> (phase 1).
 * <p/>//  w  ww.j  a v  a 2  s  .c  o m
 * <p> The implementation of this method authenticates
 * a <code>Subject</code>.  For example, it may prompt for
 * <code>Subject</code> information such
 * as a username and password and then attempt to verify the password.
 * This method saves the result of the authentication attempt
 * as private state within the LoginModule.
 * <p/>
 * <p/>
 *
 * @return true if the authentication succeeded, or false if this
 *         <code>LoginModule</code> should be ignored.
 * @throws javax.security.auth.login.LoginException
 *          if the authentication fails
 */
public boolean login() throws LoginException {
    pam = createPam();

    Callback[] callbacks = new Callback[2];
    String username = null;
    NameCallback nameCallback = new NameCallback("Enter Username: ");
    callbacks[0] = nameCallback;
    String credentials = null;
    PasswordCallback passwordCallback = new PasswordCallback("Enter Credentials: ", false);
    callbacks[1] = passwordCallback;

    try {
        callbackHandler.handle(callbacks);
    } catch (IOException e) {
        LOG.error("IOException handling login: " + e.getMessage(), e);
        throw new LoginException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        LOG.error("UnsupportedCallbackException handling login: " + e.getMessage(), e);
        throw new LoginException(e.getMessage());
    }
    username = nameCallback.getName();
    credentials = String.copyValueOf(passwordCallback.getPassword());
    boolean authenticated = false;
    PamReturnValue pamReturnValue = pam.authenticate(username, credentials);
    if (pamReturnValue.equals(PamReturnValue.PAM_SUCCESS)) {
        authenticated = true;
    } else if (pamReturnValue.equals(PamReturnValue.PAM_ACCT_EXPIRED)) {
        throw new AccountExpiredException(PamReturnValue.PAM_ACCT_EXPIRED.toString());
    } else if (pamReturnValue.equals(PamReturnValue.PAM_CRED_EXPIRED)) {
        throw new CredentialExpiredException(PamReturnValue.PAM_CRED_EXPIRED.toString());
    } else {
        throw new FailedLoginException(pamReturnValue.toString());
    }
    return authenticated;
}

From source file:com.pymmasoftware.platform.login.loginmodule.DroolsLoginModule.java

@Override
public boolean login() throws LoginException {
    succeeded = false;// w w  w.  ja v a  2 s.  c o  m
    QueryRunner queryRunner = null;
    try {
        userPrincipal = null;
        roles = null;
        if (callbackHandler == null)
            throw new LoginException("No callback handler");

        NameCallback nameCallback = new NameCallback("Username");
        PasswordCallback passwordCallback = new PasswordCallback("Password", false);

        Callback[] callbacks = new Callback[] { nameCallback, passwordCallback };
        try {
            callbackHandler.handle(callbacks);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedCallbackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        username = nameCallback.getName();
        password = new String(passwordCallback.getPassword());

        queryRunner = new QueryRunner(dataSource);

        // Create a ResultSetHandler implementation to convert the
        // first row into an Object[].
        ResultSetHandler<DroolsPrincipal> h = new ResultSetHandler<DroolsPrincipal>() {
            public DroolsPrincipal handle(ResultSet rs) throws SQLException {
                if (!rs.next()) {
                    return null;
                }

                ResultSetMetaData meta = rs.getMetaData();
                String userName = rs.getString("username");

                DroolsPrincipal droolsPrincipal = new DroolsPrincipal(userName);
                droolsPrincipal.setId(rs.getInt("id"));

                return droolsPrincipal;
            }
        };
        ResultSetHandler<List<String>> hh = new ResultSetHandler<List<String>>() {
            public List<String> handle(ResultSet rs) throws SQLException {
                if (!rs.next()) {
                    return null;
                }
                List<String> droolsGroups = new ArrayList<>();
                boolean goOne = true;
                while (goOne) {
                    String groupName = rs.getString("groups");

                    droolsGroups.add(groupName);
                    if (rs.next() == false) {
                        goOne = false;
                    }
                }
                return droolsGroups;
            }
        };

        String sqlname = "select * from guvnorusers where username = ? and password = ? ";
        DroolsPrincipal user = queryRunner.query(sqlname, h, username, password);
        if (user == null) {
            succeeded = false;
            throw new FailedLoginException("The username or The password is incorrect");
        } else {

            userPrincipal = user;
            String sqlname2 = "select groups from guvnorgroups gr,guvnorusers_groups gr_user "
                    + "where gr.id = gr_user.groups_id  " + "and gr_user.guvnorusers_id= ?";
            List<String> droolsGroups = queryRunner.query(sqlname2, hh, user.getId());
            if (droolsGroups != null) {
                int i = droolsGroups.size();
                roles = new String[i];
                i = 0;
                for (String droolsGroup : droolsGroups) {
                    roles[i] = droolsGroup;
                    i++;
                }
            }
            succeeded = true;
            return true;
        }

    } catch (Exception e) {
        throw new LoginException(e.getMessage());
    } finally {
        queryRunner = null;
    }

}

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

/**
 * //www . j  ava  2 s . c o  m
 * 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.polymap.rhei.um.auth.UmLoginModule.java

@Override
public boolean login() throws LoginException {
    Callback label = new TextOutputCallback(TextOutputCallback.INFORMATION, dialogTitle);
    NameCallback nameCallback = new NameCallback(i18n.get("username"), "default");
    PasswordCallback passwordCallback = new PasswordCallback(i18n.get("password"), false);
    try {//  ww w .j  a  v  a2s.  c om
        callbackHandler.handle(new Callback[] { label, nameCallback, passwordCallback });
    } catch (Exception e) {
        log.warn("", e);
        throw new LoginException(e.getLocalizedMessage());
    }

    String username = nameCallback.getName();
    //        if (username == null) {
    //            return false;
    //        }

    // admin
    if (username == null || username.equals("admin")) {
        // FIXME read password hash from persistent storage and check
        log.warn("!!! NO PASSWORD check for admin user yet !!!!!!");
        principal = new UserPrincipal("admin");
        return loggedIn = true;
    }

    // ordinary user
    User user = repo.findUser(username);
    log.info("username: " + user.email().get());

    if (user != null && passwordCallback.getPassword() != null) {
        String password = String.valueOf(passwordCallback.getPassword());
        if (PasswordEncryptor.instance().checkPassword(password, user.passwordHash().get())) {
            log.info("username: " + user.username().get());
            principal = new UmUserPrincipal(user);
            return loggedIn = true;
        }
    }
    return false;
}