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

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

Introduction

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

Prototype

public PasswordCallback(String prompt, boolean echoOn) 

Source Link

Document

Construct a PasswordCallback with a prompt and a boolean specifying whether the password should be displayed as it is being typed.

Usage

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.
 * /*from   w w w .j a  va2s .  c o  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: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   www  .  ja  v  a  2 s . com
            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.ibm.tivoli.tuna.jaas.ldap.LdapLoginModule.java

/**
 * Authenticate the user by prompting for a user name and password.
 * //  w  ww  . j  ava  2s .  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:net.ontopia.topicmaps.nav2.realm.TMLoginModule.java

/** 
 * Prompt the user for username and password, and verify those.
 */// w w  w  . j a  v  a2s .c  om
@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");
    }//from w ww  . j a  v a2s.com
    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   ww w.ja  v  a2  s . c o  m*/

    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.flexive.core.security.FxDefaultLogin.java

/**
 * Verify the name/password combination.
 *
 * @return true always, since this LoginModule should not be ignored.
 * @throws FailedLoginException if the authentication fails.
 * @throws LoginException       if this LoginModule is unable to perform the authentication.
 *//*from   w  w  w  .  j  a  v  a2s .  c  om*/
@Override
public boolean login() throws LoginException {
    LoginException le = null;
    try {
        // Determine username and password using the callback handler
        final Callback[] callbacks = new Callback[] { new NameCallback("user: "),
                new PasswordCallback("password: ", true), new FxCallback() };
        callbackHandler.handle(callbacks);

        FxCallback ac = ((FxCallback) callbacks[2]);
        final String username = ((NameCallback) callbacks[0]).getName();
        final PasswordCallback pc = (PasswordCallback) callbacks[1];
        final String password = new String((pc.getPassword()));
        pc.clearPassword();
        UserTicket ticket = FxAuthenticationHandler.login(username, password, ac);
        // Set the credentials and principals
        this.tempPrincipals.add(new FxPrincipal(ticket));
        // The login was successfull
        success = true;
        if (LOG.isInfoEnabled())
            LOG.info("User [" + ticket.getUserName() + "] successfully logged in, ticket=" + ticket);
    } catch (IOException exc) {
        le = new FxLoginFailedException("IOException: " + exc.getMessage(),
                FxLoginFailedException.TYPE_UNKNOWN_ERROR);
        LOG.error(le);
    } catch (UnsupportedCallbackException exc) {
        le = new FxLoginFailedException("IOException: " + exc.getMessage(),
                FxLoginFailedException.TYPE_UNKNOWN_ERROR);
        LOG.error(le);
    }
    // Log and throw exceptions
    if (le != null) {
        success = false;
        throw le;
    }
    return true;
}

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

/**
 * Send callback request for user name and user password.<br>
 * @return return a string array with index 0 of user name and index 1
 *         of password.//from www  . j av  a  2 s  .c o m
 */
private String[] getUserAndPassword() throws IOException, UnsupportedCallbackException {
    final String[] userInputs = new String[2];
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback(PROMPT_USER_NAME);
    callbacks[1] = new PasswordCallback(PROMPT_USER_PASSWORD, ECHO_ON);
    // send callback request to the authentication request sender
    mCallbackHandler.handle(callbacks);
    userInputs[0] = ((NameCallback) callbacks[0]).getName();
    userInputs[1] = String.valueOf(((PasswordCallback) callbacks[1]).getPassword());
    // clear password callback
    ((PasswordCallback) callbacks[1]).clearPassword();
    // return user name and password.
    return userInputs;
}

From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>// w  w  w  . ja v a 2  s .  com
 * This method is called to transform the mechanism-specific request message
 * acquired by calling getRequestMessage (on messageInfo) into the validated
 * application message to be returned to the message processing runtime. If
 * the received message is a (mechanism-specific) meta-message, the method
 * implementation must attempt to transform the meta-message into a
 * corresponding mechanism-specific response message, or to the validated
 * application request message. The runtime will bind a validated
 * application message into the the corresponding service invocation.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * <p/>
 * From a performance point of view this method will be called twice for
 * each resource with a security constraint on it. Resources with no
 * security constraint do not result in a call to this method.
 * 
 * @param messageInfo
 *            A contextual object that encapsulates the client request and
 *            server response objects, and that may be used to save state
 *            across a sequence of calls made to the methods of this
 *            interface for the purpose of completing a secure message
 *            exchange.
 * @param clientSubject
 *            A Subject that represents the source of the service request.
 *            It is used by the method implementation to store Principals
 *            and credentials validated in the request.
 * @param serviceSubject
 *            A Subject that represents the recipient of the service
 *            request, or null. It may be used by the method implementation
 *            as the source of Principals or credentials to be used to
 *            validate the request. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the recipient of the service request) to the
 *            Subject.
 * @return An AuthStatus object representing the completion status of the
 *         processing performed by the method. The AuthStatus values that
 *         may be returned by this method are defined as follows:
 *         <p/>
 *         <ul>
 *         <li>AuthStatus.SUCCESS when the application request message was
 *         successfully validated. The validated request message is
 *         available by calling getRequestMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_SUCCESS to indicate that
 *         validation/processing of the request message successfully
 *         produced the secured application response message (in
 *         messageInfo). The secured response message is available by
 *         calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that message validation
 *         is incomplete, and that a preliminary response was returned as
 *         the response message in messageInfo.
 *         <p/>
 *         When this status value is returned to challenge an application
 *         request message, the challenged request must be saved by the
 *         authentication module such that it can be recovered when the
 *         module's validateRequest message is called to process the request
 *         returned for the challenge.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that message validation
 *         failed and that an appropriate failure response message is
 *         available by calling getResponseMessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {
    // Get the servlet context
    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    final String auth = request.getHeader(AUTHORIZATION_HEADER);
    // Test prefix for HTTP BASIC Auth
    if (auth != null && StringUtils.startsWithIgnoreCase(auth, "basic ")) {
        // We might have a valid header, so try to decode it
        final String data = new String(Base64.decodeBase64(auth.substring(BASIC_PREFIX_LENGTH)), UTF_8);
        final int splitIndex = data.indexOf(':');
        if (splitIndex < 0) {
            return sendErrorAndAuthenticateRequest(request, response, "Wrong WWW-Authenticate header format");
        }
        final String username = data.substring(splitIndex);
        final char[] password = data.substring(splitIndex + 1, data.length()).toCharArray();

        // Prepare the JAAS callback to feed any LoginModule with user and password
        final NameCallback nameCallback = new NameCallback("username");
        nameCallback.setName(username);

        final PasswordCallback passwordCallback = new PasswordCallback(getRealm(request), false);
        passwordCallback.setPassword(password);

        final CallbackHandler delegatedHandler = new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    final Callback c = callbacks[i];
                    if (c instanceof NameCallback) {
                        ((NameCallback) c).setName(username);
                    } else if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(password);
                    } else {
                        throw new UnsupportedOperationException(
                                String.format("Callback type %s (%s) is not supported yet.", c.getClass(), c));
                    }
                }
            }
        };

        if (this.jaasContextName == null) {
            throw new UnsupportedOperationException(
                    "No delegate JAAS context found. As per JASPIC JAAS Bridge profile, this parameter is requiered.");
        }

        try {
            // Create a new JAAS context with the delegated data & try to login
            final LoginContext context = new LoginContext(this.jaasContextName, delegatedHandler);
            context.login();

            // Get the authenticated subject from the JAAS context
            Subject authenticatedSubject = context.getSubject();

            final PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(
                    authenticatedSubject, username, password);

            // notify JASPIC containerr for the name, password and subject
            this.handler.handle(new Callback[] { passwordValidationCallback });

        } catch (final LoginException ex) {
            // If there was any issue during the JAAS login, fail the process
            final AuthException aex = new AuthException(
                    String.format("Fail to login user %s with the delegated JAAS context %s", username,
                            this.jaasContextName));
            aex.initCause(ex);
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        }

    } else if (this.mandatory) {
        return sendErrorAndAuthenticateRequest(request, response,
                "AuthModule was mandatory but no valid credential was provided");
    } else {
        LOG.info("No authentication was provided bu Basic AuthModule is not mandatory so return SUCCESS.");
    }

    return AuthStatus.SUCCESS;
}

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 //from   w ww  . j av a  2 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;
}