Example usage for javax.security.auth.callback NameCallback setName

List of usage examples for javax.security.auth.callback NameCallback setName

Introduction

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

Prototype

public void setName(String name) 

Source Link

Document

Set the retrieved name.

Usage

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

protected static ModelControllerClient newModelControllerClient(final String host, final int managementPort) {
    final CallbackHandler callbackHandler = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback current : callbacks) {
                if (current instanceof NameCallback) {
                    NameCallback ncb = (NameCallback) current;
                    log.fine("ModelControllerClient is sending a username [" + managementUser + "]");
                    ncb.setName(managementUser);
                } else if (current instanceof PasswordCallback) {
                    PasswordCallback pcb = (PasswordCallback) current;
                    log.fine("ModelControllerClient is sending a password [" + managementPasword + "]");
                    pcb.setPassword(managementPasword.toCharArray());
                } else if (current instanceof RealmCallback) {
                    RealmCallback rcb = (RealmCallback) current;
                    log.fine("ModelControllerClient is sending a realm [" + rcb.getDefaultText() + "]");
                    rcb.setText(rcb.getDefaultText());
                } else {
                    throw new UnsupportedCallbackException(current);
                }//w  ww .  j av a2s .co m
            }
        }
    };

    try {
        InetAddress inetAddr = InetAddress.getByName(host);
        log.fine("Connecting a ModelControllerClient to [" + host + ":" + managementPort + "]");
        return ModelControllerClient.Factory.create(inetAddr, managementPort, callbackHandler);
    } catch (Exception e) {
        throw new RuntimeException("Failed to create management client", e);
    }
}

From source file:be.fedict.hsm.ws.impl.NamePasswordCallbackHandler.java

@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        if (callback instanceof NameCallback) {
            NameCallback nameCallback = (NameCallback) callback;
            nameCallback.setName(this.name);
        } else if (callback instanceof PasswordCallback) {
            PasswordCallback passwordCallback = (PasswordCallback) callback;
            passwordCallback.setPassword(this.password);
        }//  w w  w  .  ja v  a 2  s .c  o  m
    }
}

From source file:com.adito.activedirectory.UserPasswordCallbackHandler.java

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof NameCallback) {
            if (log.isDebugEnabled()) {
                log.debug("Handling username callback");
            }/*from  w w  w.  j a  v  a2s.c  o m*/
            NameCallback cb = (NameCallback) callbacks[i];
            cb.setName(username);

        } else if (callbacks[i] instanceof PasswordCallback) {
            if (log.isDebugEnabled()) {
                log.debug("Handling password callback");
            }
            PasswordCallback cb = (PasswordCallback) callbacks[i];
            cb.setPassword(password);

        } else {
            throw new UnsupportedCallbackException(callbacks[i]);
        }
    }
}

From source file:com.adito.pam.PAMCallbackHandler.java

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {

        /* Handles Id request */
        if (callbacks[i] instanceof NameCallback) {
            if (LOG.isDebugEnabled())
                LOG.debug("Handling username callback");
            NameCallback nc = (NameCallback) callbacks[i];
            nc.setName(username);
        }//from  w  ww .  j  a  v a 2  s  .  co  m

        /* Handles Credentitial request */
        else if (callbacks[i] instanceof PasswordCallback) {
            if (LOG.isDebugEnabled())
                LOG.debug("Handling password callback");
            PasswordCallback pc = (PasswordCallback) callbacks[i];
            pc.setPassword(password);
        }

        /* Cannot Handle other request */
        else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }

}

From source file:com.rayo.client.auth.sasl.SASLMechanism.java

/**
 * // w  w w  .  jav a2 s  .  c  o  m
 */
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof NameCallback) {
            NameCallback ncb = (NameCallback) callbacks[i];
            ncb.setName(authenticationId);
        } else if (callbacks[i] instanceof PasswordCallback) {
            PasswordCallback pcb = (PasswordCallback) callbacks[i];
            pcb.setPassword(password.toCharArray());
        } else if (callbacks[i] instanceof RealmCallback) {
            RealmCallback rcb = (RealmCallback) callbacks[i];
            rcb.setText(hostname);
        } else if (callbacks[i] instanceof RealmChoiceCallback) {
            //unused
            //RealmChoiceCallback rccb = (RealmChoiceCallback)callbacks[i];
        } else {
            throw new UnsupportedCallbackException(callbacks[i]);
        }
    }
}

From source file:org.apache.brooklyn.security.StockSecurityProviderTest.java

private LoginContext doLogin(final String username, final String password) throws LoginException {
    assertRealmRegisteredEventually(WEBCONSOLE_REALM);
    LoginContext lc = new LoginContext(WEBCONSOLE_REALM, new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                Callback callback = callbacks[i];
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(password.toCharArray());
                } else if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(username);
                }/* w  w  w  .j  a  v  a2s  . c  o m*/
            }
        }
    });
    lc.login();
    return lc;
}

From source file:br.rnp.stcfed.sts.client.impl.UsernamePasswordCallbackHandler.java

private void handleUsernameCallback(NameCallback cb) throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy K:mm:ss,S");
    System.out.println(sdf.format(new Date()));
    log.info("  ----> Setting username for the STS");
    cb.setName("stsUser");
}

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

/**
 * Authenticate a received service request.
 * <p/>//w  w w. ja v a  2s .  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:it.cnr.icar.eric.client.xml.registry.jaas.ThinClientCallbackHandler.java

/** Implementation of the handle method specified by
 * <code> javax.security.auth.callback.CallbackHandler </code>
 * @param callbacks <code>Array of 
 * javax.security.auth.callback.CallbackHandler</code>
 *
 *//*from  ww w  . ja v a 2  s .  co m*/
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof TextOutputCallback) {
            // Ignore this section for now. This will be used when a generic callback handler
            // is being implemented. In our current implementation, we are only expecting the
            //login type callback handler.
        } else if (callbacks[i] instanceof NameCallback) {
            // For now hard-code the alias of the the RegistryOperator account
            NameCallback nc = (NameCallback) callbacks[i];
            String alias = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.alias");
            if (alias == null) {
                String message = "Error: the jaxr-ebxml.security.alias " + "property must be set";
                log.error(message);
                System.err.println(message);
                alias = "";
            }
            nc.setName(alias);
        } else if (callbacks[i] instanceof PasswordCallback) {
            // For now hard-code the password of the the RegistryOperator account
            PasswordCallback pc = (PasswordCallback) callbacks[i];
            char[] password = null;
            if (handleStorePass) {
                String storepass = ProviderProperties.getInstance()
                        .getProperty("jaxr-ebxml.security.storepass");
                if (storepass == null) {
                    storepass = "ebxmlrr";
                }
                password = storepass.toCharArray();
                handleStorePass = false;
            } else {
                String keypass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.keypass");
                if (keypass == null) {
                    String message = "Error: the jaxr-ebxml.security.keypass " + "property must be set";
                    log.error(message);
                    System.err.println(message);
                    keypass = "";
                }
                password = keypass.toCharArray();
            }
            pc.setPassword(password);
        } else if (callbacks[i] instanceof ConfirmationCallback) {
            ConfirmationCallback cc = (ConfirmationCallback) callbacks[i];
            cc.setSelectedIndex(ConfirmationCallback.OK);
        } else {
            throw new UnsupportedCallbackException(callbacks[i],
                    JAXRResourceBundle.getInstance().getString("message.error.unrecognized.callback"));
        }
    }
}

From source file:org.wso2.carbon.mediator.kerberos.KerberosMediator.java

/**
 * Create call back handler using given username and password.
 *
 * @param username username.// ww w .ja  v a  2s  .co  m
 * @param password password.
 * @return CallbackHandler.
 */
private CallbackHandler getUserNamePasswordCallbackHandler(final String username, final char[] password) {

    return new CallbackHandler() {
        public void handle(final Callback[] callback) {

            for (Callback currentCallBack : callback) {
                if (currentCallBack instanceof NameCallback) {
                    final NameCallback nameCallback = (NameCallback) currentCallBack;
                    nameCallback.setName(username);
                } else if (currentCallBack instanceof PasswordCallback) {
                    final PasswordCallback passCallback = (PasswordCallback) currentCallBack;
                    passCallback.setPassword(password);
                } else {
                    log.error("Unsupported Callback class = " + currentCallBack.getClass().getName());
                }
            }
        }
    };
}