Example usage for javax.security.auth.callback Callback getClass

List of usage examples for javax.security.auth.callback Callback getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.flexive.core.security.PassiveCallbackHandler.java

/**
 * Handles the specified set of Callbacks. Uses the username and password that were supplied to our
 * constructor to popluate the Callbacks.
 * <p/>//from www .  j  a  v  a  2 s  . com
 * This class supports NameCallback and PasswordCallback.
 *
 * @param callbacks the callbacks to handle
 * @throws IOException                  if an input or output error occurs.
 * @throws UnsupportedCallbackException if the callback is not an instance of NameCallback or PasswordCallback
 */
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

    for (Callback callback : callbacks) {
        if (callback == null)
            continue;
        if (callback instanceof NameCallback) {
            ((NameCallback) callback).setName(username);
        } else if (callback instanceof PasswordCallback) {
            ((PasswordCallback) callback).setPassword(password);
        } else if (callback instanceof FxCallback) {
            FxCallback ac = ((FxCallback) callback);
            ac.setTakeOverSession(takeOverSession);
            ac.setDataSource(ds);
            ac.setSessionContext(ctx);
        } else {
            UnsupportedCallbackException uce = new UnsupportedCallbackException(callback,
                    "Callback class [" + callback.getClass() + "] not supported");
            LOG.error(uce);
            throw uce;
        }
    }

}

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

/**
 * Authenticate a received service request.
 * <p/>// w ww  . j a  v  a  2  s .c  o  m
 * 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:org.wso2.carbon.mediator.kerberos.KerberosMediator.java

/**
 * Create call back handler using given username and password.
 *
 * @param username username./*  w  ww  .  j a v a  2 s  .  com*/
 * @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());
                }
            }
        }
    };
}

From source file:nl.nn.adapterframework.util.CredentialFactory.java

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    log.info("Handling callbacks for alias [" + getAlias() + "]");
    for (int i = 0; i < callbacks.length; i++) {
        Callback cb = callbacks[i];
        //         log.info(i+") "+cb.getClass().getName()+" "+ToStringBuilder.reflectionToString(cb));
        Class cbc = cb.getClass();
        if (cbc.getName().endsWith("MappingPropertiesCallback")) { // Websphere 6
            try {
                Map mappingProperties = new HashMap();
                mappingProperties.put("com.ibm.mapping.authDataAlias", getAlias());
                ClassUtils.invokeSetter(cb, "setProperties", mappingProperties, Map.class);
                log.debug(//from  ww  w. j a v a2 s  .  c o  m
                        "MappingPropertiesCallback.properties set to entry key [com.ibm.mapping.authDataAlias], value ["
                                + getAlias() + "]");
                continue;
            } catch (Exception e) {
                log.warn("exception setting alias [" + getAlias() + "] on MappingPropertiesCallback", e);
            }
        }
        if (cbc.getName().endsWith("AuthDataAliasCallback")) { // Websphere 5
            try {
                log.info("setting alias of AuthDataAliasCallback to alias [" + getAlias() + "]");
                ClassUtils.invokeSetter(cb, "setAlias", getAlias());
                continue;
            } catch (Exception e) {
                log.warn("exception setting alias [" + getAlias() + "] on AuthDataAliasCallback", e);
            }
        }
        if (cb instanceof NameCallback) {
            NameCallback ncb = (NameCallback) cb;
            log.info("setting name of NameCallback to alias [" + getAlias() + "]");
            ncb.setName(getAlias());
            continue;
        }
        log.debug("ignoring callback of type [" + cb.getClass().getName() + "] for alias [" + getAlias() + "]");
        //         log.debug("contents of callback ["+ToStringBuilder.reflectionToString(cb)+"]");
        //         Class itf[] = cbc.getInterfaces();
        //         for (int j=0; j<itf.length; j++) {
        //            log.info("interface "+j+": "+itf[j].getName());
        //         }
        //         Method methods[] = cbc.getMethods();
        //         for (int j=0; j<methods.length; j++) {
        //            log.info("method "+j+": "+methods[j].getName()+", "+methods[j].toString());
        //         }
        //         if (cb instanceof ChoiceCallback) {
        //            ChoiceCallback ccb = (ChoiceCallback) cb;
        //            log.info("ChoiceCallback: "+ccb.getPrompt());
        //         }

    }
    log.info("Handled callbacks for alias [" + getAlias() + "]");
}

From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java

/**
 * SaslServer will use this method to call various callbacks, depending on the SASL
 * mechanism in use for a session.//from  w  ww  .j a va 2  s  .c o  m
 * 
 * @param callbacks An array of one or more callbacks.
 */
public void handle(Callback[] callbacks) {
    for (int i = 0; i < callbacks.length; i++) {
        Callback callback = callbacks[i];

        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing callback {} of {}: {}", callback.getClass(), (i + 1), callbacks.length);
        }

        if (callback instanceof NameCallback) {
            NameCallback nameCB = (NameCallback) callback;
            LOG.debug("NameCallback default name:  {}", nameCB.getDefaultName());

            username = nameCB.getDefaultName();
        } else if (callback instanceof RealmCallback) {
            RealmCallback realmCB = (RealmCallback) callback;
            LOG.debug("RealmCallback default text:  {}", realmCB.getDefaultText());

            realm = realmCB.getDefaultText();
        } else if (callback instanceof PasswordCallback) {
            PasswordCallback passwordCB = (PasswordCallback) callback;
            Attribute userPassword = lookupPassword(getUsername(), getRealm());

            if (userPassword != null) {
                // We assume that we have only one password available
                byte[] password = userPassword.get().getBytes();

                String strPassword = Strings.utf8ToString(password);
                passwordCB.setPassword(strPassword.toCharArray());
            }
        } else if (callback instanceof AuthorizeCallback) {
            AuthorizeCallback authorizeCB = (AuthorizeCallback) callback;

            // hnelson (CRAM-MD5, DIGEST-MD5)
            // hnelson@EXAMPLE.COM (GSSAPI)
            LOG.debug("AuthorizeCallback authnID:  {}", authorizeCB.getAuthenticationID());

            // hnelson (CRAM-MD5, DIGEST-MD5)
            // hnelson@EXAMPLE.COM (GSSAPI)
            LOG.debug("AuthorizeCallback authzID:  {}", authorizeCB.getAuthorizationID());

            // null (CRAM-MD5, DIGEST-MD5, GSSAPI)
            LOG.debug("AuthorizeCallback authorizedID:  {}", authorizeCB.getAuthorizedID());

            // false (CRAM-MD5, DIGEST-MD5, GSSAPI)
            LOG.debug("AuthorizeCallback isAuthorized:  {}", authorizeCB.isAuthorized());

            try {
                authorize(authorizeCB);
            } catch (Exception e) {
                // TODO - figure out how to handle this properly.
                throw new RuntimeException(I18n.err(I18n.ERR_677), e);
            }
        }
    }
}

From source file:org.apache.ws.security.NamePasswordCallbackHandler.java

private boolean invokePasswordCallback(Callback callback) {
    String cbname = passwordCallbackName == null ? PASSWORD_CALLBACK_NAME : passwordCallbackName;
    for (Class<?> arg : PASSWORD_CALLBACK_TYPES) {
        try {/*from  ww w  .j av a2s. co  m*/
            Method method = callback.getClass().getMethod(cbname, arg);
            method.invoke(callback, arg == String.class ? password : password.toCharArray());
            return true;
        } catch (Exception e) {
            // ignore and continue
            log.warn(e.toString());
        }
    }
    return false;
}

From source file:org.josso.jaspi.agent.JASPICallbackHandler.java

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    if (callbacks.length > 0) {
        for (Callback callback : callbacks) {
            if (callback instanceof CallerPrincipalCallback) {
                callback = this.callerPrincipalCallback;
            } else if (callback instanceof PasswordValidationCallback) {
                callback = this.passwordValidationCallback;
            } else if (callback instanceof GroupPrincipalCallback) {
                callback = this.groupPrincipalCallback;
            } else
                log.trace("Callback " + callback.getClass().getCanonicalName() + " not supported");
        }/*w  w w .j  a v  a  2  s . c  o  m*/
    }
}

From source file:org.kalypso.test.bsu.wfs.SingleSignonTest.java

public void testSigngleSignon() throws Exception {
    try {//from   w ww  . j a  va 2  s .  c o  m
        copy(new File("D:/eclipse3.1/tmp/web_FlowsAStestLogin.html"));
        LoginContext loginContext = null;
        System.setProperty("java.security.auth.login.config", "D:/eclipse3.1/tmp/jaasConf.txt");
        // Login-Kontext fr die Konfiguration "Demo" erzeugen
        // loginContext = new LoginContext( "Demo" );
        loginContext = new LoginContext("Demo", new CallbackHandler() {

            public void handle(Callback[] callbacks) {
                for (int i = 0; i < callbacks.length; i++) {
                    Callback callback = callbacks[i];
                    if (callback instanceof NameCallback) {
                        final NameCallback nCall = (NameCallback) callback;
                        System.out.println(nCall.getPrompt());
                        nCall.setName("Flowsad");
                    } else if (callback instanceof PasswordCallback) {
                        final PasswordCallback call = (PasswordCallback) callback;
                        System.out.println(call.getPrompt());
                        call.setPassword(new char[] { ' ', ' ', });
                    } else
                        System.out.println("unknown Callback: " + callback.getClass().getName());
                }
            }

        });
        // Durchfhrung des Logins
        loginContext.login();
        System.out.println("authentication succeeded");

        // Die Principals ermitteln...
        Set principals = loginContext.getSubject().getPrincipals();
        // ...und in einer Iteration ausgeben
        Iterator it = principals.iterator();
        Principal p;
        while (it.hasNext()) {
            p = (Principal) it.next();
            System.out.println(p);
        }
        System.out.println("logging out...");
        copy(new File("D:/eclipse3.1/tmp/web_FlowsAdmitLogin.html"));

        loginContext.logout();
    } catch (Exception e) {
        System.out.println("authentication failed");
        throw e;
    }
}

From source file:org.marketcetera.modules.remote.receiver.ClientLoginModuleTest.java

/**
 * test unsupported callbacks/*from w  ww. j  a v  a  2 s  .co m*/
 * @throws Exception if there was failure
 */
@Test
public void unsupportedCallback() throws Exception {
    doNotHandleCallbacks = true;
    UnsupportedCallbackException uce = new UnsupportedCallbackException(
            new NameCallback(Messages.PROMPT_USERNAME.getText()));
    LoginException ex = attemptLogin(getTestUsername(), getTestPassword(), LoginException.class,
            uce.getMessage());
    assertNotNull(ex.getCause());
    assertTrue(ex.getCause() instanceof UnsupportedCallbackException);
    Callback callback = ((UnsupportedCallbackException) ex.getCause()).getCallback();
    assertNotNull(callback);
    assertTrue(callback.getClass().toString(), callback instanceof NameCallback);
    org.junit.Assert.assertEquals(Messages.PROMPT_USERNAME.getText(), ((NameCallback) callback).getPrompt());
}

From source file:org.trypticon.xmpp.util.FixedCallbackHandler.java

/**
 * Handles multiple callbacks./*from ww  w .  jav a  2s  . c o  m*/
 *
 * @param callbacks the callbacks to handle.
 * @throws IOException
 * @throws UnsupportedCallbackException
 */
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (Callback callback : callbacks) {
        if (callback instanceof NameCallback) {
            log.debug("Name callback being responded to with name '" + name + "'.");
            ((NameCallback) callback).setName(name);
        } else if (callback instanceof PasswordCallback) {
            log.debug("Password callback being responded to.");
            ((PasswordCallback) callback).setPassword(password);
        } else {
            log.warn("Unknown callback of type " + callback.getClass().getName());
        }
    }
}