Search in sources :

Example 16 with Callback

use of javax.security.auth.callback.Callback in project OpenAM by OpenRock.

the class SAML2 method initiateSAMLLoginAtIDP.

/**
     * Performs similar to SPSSOFederate.initiateAuthnRequest by returning to the next auth stage
     * with a redirect (either GET or POST depending on the config) which triggers remote IdP authentication.
     */
private int initiateSAMLLoginAtIDP(final HttpServletResponse response, final HttpServletRequest request) throws SAML2Exception, AuthLoginException {
    if (reqBinding == null) {
        reqBinding = SAML2Constants.HTTP_REDIRECT;
    }
    final String spEntityID = SPSSOFederate.getSPEntityId(metaAlias);
    final IDPSSODescriptorElement idpsso = SPSSOFederate.getIDPSSOForAuthnReq(realm, entityName);
    final SPSSODescriptorElement spsso = SPSSOFederate.getSPSSOForAuthnReq(realm, spEntityID);
    if (idpsso == null || spsso == null) {
        return processError(bundle.getString("samlLocalConfigFailed"), "SAML2 :: initiateSAMLLoginAtIDP() : {}", bundle.getString("samlLocalConfigFailed"));
    }
    final String ssoURL = SPSSOFederate.getSSOURL(idpsso.getSingleSignOnService(), reqBinding);
    final List extensionsList = SPSSOFederate.getExtensionsList(spEntityID, realm);
    final Map<String, Collection<String>> spConfigAttrsMap = SPSSOFederate.getAttrsMapForAuthnReq(realm, spEntityID);
    authnRequest = SPSSOFederate.createAuthnRequest(realm, spEntityID, params, spConfigAttrsMap, extensionsList, spsso, idpsso, ssoURL, false);
    final AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, null, authnRequest, null, params);
    synchronized (SPCache.requestHash) {
        SPCache.requestHash.put(authnRequest.getID(), reqInfo);
    }
    saveAuthnRequest(authnRequest, reqInfo);
    final Callback[] nextCallbacks = getCallback(REDIRECT);
    final RedirectCallback redirectCallback = (RedirectCallback) nextCallbacks[0];
    setCookiesForRedirects(request, response);
    //we only handle Redirect and POST
    if (SAML2Constants.HTTP_POST.equals(reqBinding)) {
        final String postMsg = SPSSOFederate.getPostBindingMsg(idpsso, spsso, spConfigAttrsMap, authnRequest);
        configurePostRedirectCallback(postMsg, ssoURL, redirectCallback);
    } else {
        final String authReqXMLString = authnRequest.toXMLString(true, true);
        final String redirectUrl = SPSSOFederate.getRedirect(authReqXMLString, null, ssoURL, idpsso, spsso, spConfigAttrsMap);
        configureGetRedirectCallback(redirectUrl, redirectCallback);
    }
    return REDIRECT;
}
Also used : RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) Callback(javax.security.auth.callback.Callback) PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) AuthnRequestInfo(com.sun.identity.saml2.profile.AuthnRequestInfo) Collection(java.util.Collection) List(java.util.List) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 17 with Callback

use of javax.security.auth.callback.Callback in project OpenAM by OpenRock.

the class AuthUtils method authenticate.

public static SSOToken authenticate(String realm, String userName, String password) throws Exception {
    AuthContext lc = new AuthContext(realm);
    lc.login();
    while (lc.hasMoreRequirements()) {
        Callback[] callbacks = lc.getRequirements();
        for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
                NameCallback nc = (NameCallback) callbacks[i];
                nc.setName(userName);
            } else if (callbacks[i] instanceof PasswordCallback) {
                PasswordCallback pc = (PasswordCallback) callbacks[i];
                pc.setPassword(password.toCharArray());
            } else {
                throw new Exception("No callback");
            }
        }
        lc.submitRequirements(callbacks);
    }
    return (lc.getStatus() != AuthContext.Status.SUCCESS) ? null : lc.getSSOToken();
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) AuthContext(com.sun.identity.authentication.AuthContext) PasswordCallback(javax.security.auth.callback.PasswordCallback)

Example 18 with Callback

use of javax.security.auth.callback.Callback in project OpenAM by OpenRock.

the class OpenAMAuthHandler method startAuthProcess.

/**
     * Starts the authentication process by creating a new AuthContextLocale and the submitted username and password and
     * passing those to the first module in the authentication chain and completing authentication if that is the only
     * module in the chain or crafting a suitable challenge response to start gathering values for the next module's
     * callbacks. Returns true if authentication was started and user requirements beyond username and password can now
     * be solicited or false if starting failed and a reject message has already been generated.
     *
     * @param response
     *            the response object for the radius request
     * @param reqAttsMap
     * @param credential
     */
private ContextHolder startAuthProcess(ContextHolder holder, RadiusResponse response, UserNameAttribute usrAtt, String credential) {
    LOG.message("Entering OpenAMAuthHandler.startAuthProcess");
    // now create an authContext and trigger loading of whatever authN modules will be used
    try {
        holder.setAuthContext(amAuthFactory.getAuthContext(realm));
    } catch (final AuthLoginException e) {
        LOG.error("Unable to start create " + AuthContext.class.getName() + ". Denying Access.", e);
        rejectAccessAndTerminateProcess(response, holder);
        LOG.message("Leaving OpenAMAuthHandler.startAuthProcess");
        return holder;
    }
    try {
        holder.getAuthContext().login(AuthContext.IndexType.SERVICE, authChain);
    } catch (final AuthLoginException e) {
        LOG.error("Unable to start login process. Denying Access.", e);
        rejectAccessAndTerminateProcess(response, holder);
        LOG.message("Leaving OpenAMAuthHandler.startAuthProcess");
        return holder;
    }
    if (!isNextCallbackSetAvailable(response, holder)) {
        // since we must have callbacks when starting up the authn process to handle username and password.
        if (holder.getAuthPhase() != ContextHolder.AuthPhase.TERMINATED) {
            LOG.error("Unable to start login process. No callbacks available. Denying Access.");
            rejectAccessAndTerminateProcess(response, holder);
        }
        LOG.message("Leaving OpenAMAuthHandler.startAuthProcess");
        return holder;
    }
    // for RADIUS we have username and password within the initial request. Therefore, the first module in the
    // chain must support a name and password callback. so walk the set of callbacks representing the first
    // module and inject and then test for further module requirements. if any exist then we must craft a
    // suitable challenge response and await the next request that gets submitted after the radius client has
    // gathered those values.
    boolean injectedUsr = false;
    boolean injectedPwd = false;
    final Callback[] callbacks = holder.getCallbacks();
    for (int i = holder.getIdxOfCurrentCallback(); i < callbacks.length; i++) {
        if (callbacks[i] instanceof NameCallback) {
            holder.incrementIdxOfCurrentCallback();
            final NameCallback nm = (NameCallback) callbacks[i];
            nm.setName(usrAtt.getName());
            injectedUsr = true;
        } else if (callbacks[i] instanceof PasswordCallback) {
            holder.incrementIdxOfCurrentCallback();
            final PasswordCallback pc = (PasswordCallback) callbacks[i];
            pc.setPassword(credential.toCharArray());
            injectedPwd = true;
        } else {
            holder.incrementIdxOfCurrentCallback();
        }
    }
    // did we have NameCallback and PasswordCallback to inject the username and password?
    if (injectedUsr && injectedPwd) {
        holder.getAuthContext().submitRequirements(callbacks);
        // cLog.warning("--- submitting usr/pwd in startAuthProcess, set callbacks=null");
        // triggers loading of next set, conveys to gatherer that we have just started
        holder.setCallbacks(null);
    } else {
        // if we get here and didn't submit, then the callbacks array representing the requirements of the first
        // module in the chain didn't support username and password. So log the error and reject access.
        final String msg = "First callback set for first module" + (holder.getModuleName() != null ? " '" + holder.getModuleName() + "'" : "") + " in authentication chain '" + this.authChain + "' does not support Username and Password callbacks. Denying Access.";
        LOG.error(msg);
        rejectAccessAndTerminateProcess(response, holder);
    }
    // if we get here then we successfully started the authN process
    holder.setAuthPhase(ContextHolder.AuthPhase.GATHERING_INPUT);
    LOG.message("Leaving OpenAMAuthHandler.startAuthProcess");
    return holder;
}
Also used : PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) HttpCallback(com.sun.identity.authentication.spi.HttpCallback) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) NameCallback(javax.security.auth.callback.NameCallback) ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) PasswordCallback(javax.security.auth.callback.PasswordCallback)

Example 19 with Callback

use of javax.security.auth.callback.Callback in project OpenAM by OpenRock.

the class OpenAMAuthHandler method isNextCallbackSetAvailable.

/**
     * Obtains the next set of OpenAM authorization callbacks, updating our info set or sets the callbacks to null if
     * unable to acquire and update the info set and sends an accessReject response in that case. Returns true if
     * callback set was loaded into holder. Returns false if they couldn't be loaded or were empty which may be a valid
     * state depending on the caller. Sets holder.authPhase = TERMINATED if something happened causing the
     * authentication process to fail.
     *
     * @param context
     * @param holder
     * @return
     */
private boolean isNextCallbackSetAvailable(RadiusResponse response, ContextHolder holder) {
    final boolean moreCallbacksAvailable = holder.getAuthContext().hasMoreRequirements();
    if (!moreCallbacksAvailable) {
        // cLog.warning("--- no callbacks available, set callbacks=null in isNextCallbackSetAvailable");
        holder.setCallbacks(null);
        return false;
    }
    // true means do NOT filter PagePropertiesCallbacks
    final Callback[] callbacks = holder.getAuthContext().getRequirements(true);
    holder.setCallbacks(callbacks);
    if (holder.getCallbacks() == null) {
        // cLog.warning("--- callbacks == null after ac.getReqs() called in isNextCallbackSetAvailable");
        return false;
    }
    // process page properties piece
    if (callbacks[0] instanceof PagePropertiesCallback) {
        // not a formal callback, openam specific
        final PagePropertiesCallback pp = (PagePropertiesCallback) callbacks[0];
        holder.setCallbackSetProps(pp);
        // since page properties cb is at zero index
        holder.setIdxOfCurrentCallback(1);
        final String moduleName = pp.getModuleName();
        if (!moduleName.equals(holder.getModuleName())) {
            // entering new module
            holder.setModuleName(moduleName);
            holder.incrementChainModuleIndex();
            holder.setIdxOfCallbackSetInModule(0);
        // cLog.warning("New Module Incurred: " + holder.moduleName + " with callbacks["
        // + holder.callbacks.length + "]");
        } else {
            holder.incrementIdxOfCallbackSetInModule();
        // cLog.warning("New Callback Set[" + holder.callbacks.length + "] Incurred in Module: "
        // + holder.moduleName);
        }
        // update the
        holder.setMillisExpiryForCurrentCallbacks(1000L * pp.getTimeOutValue());
        holder.setMillisExpiryPoint(System.currentTimeMillis() + holder.getMillisExpiryForCurrentCallbacks());
    } else {
        LOG.error("Callback at index 0 is not of type PagePropertiesCallback!!!");
        rejectAccessAndTerminateProcess(response, holder);
        return false;
    }
    // now fail fast if we find unsupportable callback types
    boolean httpCbIncurred = false;
    boolean redirectCbIncurred = false;
    for (int i = 1; i < callbacks.length; i++) {
        final Callback cb = callbacks[i];
        if (cb instanceof HttpCallback) {
            httpCbIncurred = true;
            break;
        } else if (cb instanceof RedirectCallback) {
            redirectCbIncurred = true;
            break;
        }
    }
    if (httpCbIncurred || redirectCbIncurred) {
        LOG.error("Radius can not support " + (httpCbIncurred ? HttpCallback.class.getSimpleName() : RedirectCallback.class.getSimpleName()) + " used by module " + holder.getChainModuleIndex() + " with name " + holder.getModuleName() + " in chain '" + this.authChain + "'. Denying Access.");
        rejectAccessAndTerminateProcess(response, holder);
        return false;
    }
    return true;
}
Also used : RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) HttpCallback(com.sun.identity.authentication.spi.HttpCallback) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) NameCallback(javax.security.auth.callback.NameCallback) ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) Callback(javax.security.auth.callback.Callback) PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) HttpCallback(com.sun.identity.authentication.spi.HttpCallback)

Example 20 with Callback

use of javax.security.auth.callback.Callback in project OpenAM by OpenRock.

the class OpenAMAuthHandler method injectAnswerForCallback.

/**
     * Injects the user's answer into the callback currently waiting for one with proper handling for the type of
     * callback. Increments the index of the current callback and returns true if the value was successly injected or
     * false if it failed and terminated authentication.
     *
     * @param respHandler
     * @param holder
     * @param answer
     */
private boolean injectAnswerForCallback(RadiusResponse response, ContextHolder holder, String answer) {
    final Callback[] callbacks = holder.getCallbacks();
    if (callbacks == null) {
        return false;
    }
    final Callback cb = callbacks[holder.getIdxOfCurrentCallback()];
    // so that we are sitting on that callback in the next call
    holder.incrementIdxOfCurrentCallback();
    if (cb instanceof NameCallback) {
        final NameCallback nc = (NameCallback) cb;
        ((NameCallback) cb).setName(answer);
    // cLog.warning("--- set NameCallback=" + answer);
    } else if (cb instanceof PasswordCallback) {
        final PasswordCallback pc = (PasswordCallback) cb;
        pc.setPassword(answer.toCharArray());
    // cLog.warning("--- set PasswordCallback=" + answer);
    } else if (cb instanceof ChoiceCallback) {
        final ChoiceCallback cc = (ChoiceCallback) cb;
        final int maxIdx = cc.getChoices().length - 1;
        if ("".equals(answer)) {
            // user didn't provide an answer so accept default
            cc.setSelectedIndex(cc.getDefaultChoice());
            // cLog.warning("--- set ChoiceCallback=default(" + cc.getDefaultChoice() + ")");
            return true;
        }
        final boolean answerContainsSeparator = answer.indexOf(' ') != -1;
        if (cc.allowMultipleSelections() && answerContainsSeparator) {
            // may need to parse answer
            if (answerContainsSeparator) {
                final String[] answers = answer.split(" ");
                final List<Integer> idxs = new ArrayList<Integer>();
                for (final String ans : answers) {
                    if (!"".equals(ans)) {
                        final int idx = parseInt(response, ans, answer, maxIdx, holder, cb);
                        if (idx == -1) {
                            // cLog.warning("--- ChoiceCallback failed parsing mult");
                            return false;
                        }
                        idxs.add(idx);
                    }
                }
                final int[] selected = new int[idxs.size()];
                for (int i = 0; i < selected.length; i++) {
                    selected[i] = idxs.get(i);
                }
                cc.setSelectedIndexes(selected);
            // cLog.warning("--- set ChoiceCallback=" + Arrays.asList(selected));
            }
        } else {
            final int idx = parseInt(response, answer, answer, maxIdx, holder, cb);
            if (idx == -1) {
                // cLog.warning("--- ChoiceCallback failed parsing");
                return false;
            }
            cc.setSelectedIndex(idx);
        // cLog.warning("--- set ChoiceCallback=" + idx);
        }
    } else if (cb instanceof ConfirmationCallback) {
        final ConfirmationCallback cc = (ConfirmationCallback) cb;
        final int maxIdx = cc.getOptions().length - 1;
        if ("".equals(answer)) {
            // user didn't provide an answer so accept default
            cc.setSelectedIndex(cc.getDefaultOption());
            // cLog.warning("--- set ConfirmationCallback=default(" + cc.getDefaultOption() + ")");
            return true;
        }
        final int idx = parseInt(response, answer, answer, maxIdx, holder, cb);
        if (idx == -1) {
            // cLog.warning("--- ConfirmationCallback failed parsing");
            return false;
        }
        cc.setSelectedIndex(idx);
    // cLog.warning("--- set ConfirmationCallback=" + idx);
    } else {
        LOG.error("Unrecognized callback type '" + cb.getClass().getSimpleName() + "' while processing challenge response. Unable to submit answer. Denying Access.");
        rejectAccessAndTerminateProcess(response, holder);
        return false;
    }
    // reset the timeout since we just received confirmation that the user is still there.
    holder.setMillisExpiryPoint(System.currentTimeMillis() + holder.getMillisExpiryForCurrentCallbacks());
    return true;
}
Also used : ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) ArrayList(java.util.ArrayList) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) PagePropertiesCallback(com.sun.identity.authentication.spi.PagePropertiesCallback) HttpCallback(com.sun.identity.authentication.spi.HttpCallback) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) ChoiceCallback(javax.security.auth.callback.ChoiceCallback) NameCallback(javax.security.auth.callback.NameCallback) ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback)

Aggregations

Callback (javax.security.auth.callback.Callback)390 NameCallback (javax.security.auth.callback.NameCallback)250 PasswordCallback (javax.security.auth.callback.PasswordCallback)245 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)210 IOException (java.io.IOException)141 LoginException (javax.security.auth.login.LoginException)89 CallbackHandler (javax.security.auth.callback.CallbackHandler)76 Subject (javax.security.auth.Subject)52 ChoiceCallback (javax.security.auth.callback.ChoiceCallback)52 Test (org.testng.annotations.Test)42 FailedLoginException (javax.security.auth.login.FailedLoginException)41 ConfirmationCallback (javax.security.auth.callback.ConfirmationCallback)38 Principal (java.security.Principal)37 HashMap (java.util.HashMap)37 LoginContext (javax.security.auth.login.LoginContext)37 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)31 Test (org.junit.Test)31 RealmCallback (javax.security.sasl.RealmCallback)30 AuthorizeCallback (javax.security.sasl.AuthorizeCallback)29 HttpServletRequest (javax.servlet.http.HttpServletRequest)28