Search in sources :

Example 36 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class DevicePrintAuthenticationServiceTest method shouldThrowExceptionWhenSubmittedtOTPWithIncorrectErrorCode.

/**
     * 6) third call, using OPT, 2 - OPT code submitted, with incorrect code - should throw exception
     */
@Test
public void shouldThrowExceptionWhenSubmittedtOTPWithIncorrectErrorCode() throws AuthLoginException {
    //Given
    Callback[] callbacks = new Callback[2];
    PasswordCallback smsOTPCallback = mock(PasswordCallback.class);
    ConfirmationCallback confirmationCallback = mock(ConfirmationCallback.class);
    int state = 2;
    String otpCode = "OTPCODEWRONG";
    callbacks[0] = smsOTPCallback;
    callbacks[1] = confirmationCallback;
    given(smsOTPCallback.getPassword()).willReturn(otpCode.toCharArray());
    given(confirmationCallback.getSelectedIndex()).willReturn(0);
    given(hotpService.isValidHOTP("OTPCODEWRONG")).willReturn(false);
    //When
    boolean exceptionCaught = false;
    try {
        devicePrintAuthenticationService.process(callbacks, state);
        fail();
    } catch (AuthLoginException e) {
        exceptionCaught = true;
    }
    //Then
    assertTrue(exceptionCaught);
}
Also used : 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) ConfirmationCallback(javax.security.auth.callback.ConfirmationCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) DevicePrint(org.forgerock.openam.authentication.modules.deviceprint.model.DevicePrint) Test(org.testng.annotations.Test)

Example 37 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class DevicePrintAuthenticationServiceTest method shouldThrowExceptionStateIsNotKnown.

@Test
public void shouldThrowExceptionStateIsNotKnown() throws AuthLoginException {
    //Given
    Callback[] callbacks = new Callback[0];
    int state = 4;
    //When
    boolean exceptionCaught = false;
    try {
        devicePrintAuthenticationService.process(callbacks, state);
        fail();
    } catch (AuthLoginException e) {
        exceptionCaught = true;
    }
    //Then
    assertTrue(exceptionCaught);
}
Also used : 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) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) DevicePrint(org.forgerock.openam.authentication.modules.deviceprint.model.DevicePrint) Test(org.testng.annotations.Test)

Example 38 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class RestAuthenticationHandler method authenticate.

/**
     * Handles either the creation or retrieval of the Login Process, dependent on if the request is a new
     * authentication request or a continuation of one.
     *
     * @param request The HttpServletRequest.
     * @param response The HttpServletResponse.
     * @param postBody The post body of the request.
     * @param authIndexType The authentication index type.
     * @param indexValue The authentication index value.
     * @param sessionUpgradeSSOTokenId The SSO Token Id of the user's current session, null if not performing a session
     *                                 upgrade.
     * @return The Response of the authentication request.
     */
private JsonValue authenticate(HttpServletRequest request, HttpServletResponse response, JsonValue postBody, String authIndexType, String indexValue, String sessionUpgradeSSOTokenId) throws RestAuthException {
    LoginProcess loginProcess = null;
    try {
        AuthIndexType indexType = getAuthIndexType(authIndexType);
        String authId = null;
        String sessionId = null;
        if (postBody != null) {
            authId = getAuthId(postBody);
            if (authId != null) {
                SignedJwt jwt = authIdHelper.reconstructAuthId(authId);
                sessionId = getSessionId(jwt);
                indexType = getAuthIndexType(jwt);
                indexValue = getAuthIndexValue(jwt);
                String realmDN = getRealmDomainName(jwt);
                AuditRequestContext.putProperty(SESSION_ID, sessionId);
                authIdHelper.verifyAuthId(realmDN, authId);
            }
        }
        LoginConfiguration loginConfiguration = new LoginConfiguration().httpRequest(request).httpResponse(response).indexType(indexType).indexValue(indexValue).sessionId(sessionId).forceAuth(request.getParameter(AuthUtils.FORCE_AUTH)).sessionUpgrade(sessionUpgradeSSOTokenId);
        loginProcess = loginAuthenticator.getLoginProcess(loginConfiguration);
        return processAuthentication(request, response, postBody, authId, loginProcess, loginConfiguration);
    } catch (RestAuthException e) {
        if (loginProcess != null) {
            String failureUrl = urlValidator.getRedirectUrl(loginProcess.getAuthContext().getOrgDN(), loginProcess.getFailureURL(), null);
            e.setFailureUrl(failureUrl);
        }
        throw e;
    } catch (L10NMessageImpl e) {
        throw new RestAuthException(amAuthErrorCodeResponseStatusMapping.getAuthLoginExceptionResponseStatus(e.getErrorCode()), e);
    } catch (JsonException e) {
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, e);
    } catch (SignatureException e) {
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, e);
    } catch (AuthLoginException e) {
        throw new RestAuthException(amAuthErrorCodeResponseStatusMapping.getAuthLoginExceptionResponseStatus(e.getErrorCode()), e);
    } catch (JwsSigningException jse) {
        DEBUG.error("JwsSigningException", jse);
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, "JwsSigningException, " + jse.getMessage());
    }
}
Also used : RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) JsonException(org.forgerock.json.JsonException) JwsSigningException(org.forgerock.json.jose.exceptions.JwsSigningException) L10NMessageImpl(com.sun.identity.shared.locale.L10NMessageImpl) AuthIndexType(org.forgerock.openam.core.rest.authn.core.AuthIndexType) LoginConfiguration(org.forgerock.openam.core.rest.authn.core.LoginConfiguration) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) SignatureException(java.security.SignatureException) LoginProcess(org.forgerock.openam.core.rest.authn.core.LoginProcess)

Example 39 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class AMLoginContext method executeLogin.

/**
     * Starts login process, the map passed to this method is the parameters
     * required to start the login process. These parameters are
     * <code>indexType</code>, <code>indexName</code> , <code>principal</code>,
     * <code>subject</code>, <code>password</code>,
     * <code>organization name</code>. Based on these parameters Module
     * Configuration name is retrieved using Configuration component. Creates
     * a new LoginContext and starts login process and returns. On error
     * LoginException is thrown.
     *
     * @param loginParamsMap login parameters HashMap
     * @throws AuthLoginException if execute login fails
     */
public void executeLogin(Map<String, Object> loginParamsMap) throws AuthLoginException {
    boolean errorState = false;
    internalAuthError = false;
    processDone = false;
    isFailed = false;
    setLoginHash();
    /*
         * Ensure loginState created and loginParamsMap provided
         */
    if (loginState == null || loginParamsMap == null) {
        debug.error("Error: loginState or loginParams is null");
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        if (loginState != null) {
            loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        }
        setErrorMsgAndTemplate();
        internalAuthError = true;
        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_ERROR, null);
    }
    /*
         * Lookup resource bundle and locale specific settings based on locale associated with LoginState
         */
    java.util.Locale loginLocale = com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale());
    bundle = AMResourceBundleCache.getInstance().getResBundle(BUNDLE_NAME, loginLocale);
    exceedRetryLimit = AMResourceBundleCache.getInstance().getResBundle("amAuthLDAP", loginLocale).getString(ISAuthConstants.EXCEED_RETRY_LIMIT);
    if (debug.messageEnabled()) {
        debug.message("LoginState : " + loginState);
    }
    /*
         * Handle redirection if applicable
         */
    String redirectUrl = (String) loginParamsMap.get(AuthContextLocal.REDIRECT_URL);
    if (redirectUrl != null) {
        // Resource/IP/Env based auth case with Redirection Advice
        Callback[] redirectCallback = new Callback[1];
        redirectCallback[0] = new RedirectCallback(redirectUrl, null, "GET");
        if (isPureJAAS()) {
            loginState.setReceivedCallback_NoThread(redirectCallback);
        } else {
            loginState.setReceivedCallback(redirectCallback, this);
        }
        return;
    }
    /*
         * Initialize instance fields from loginParamsMap
         */
    parseLoginParams(loginParamsMap);
    /*
         * Copy orgDN and clientType values from LoginState
         */
    if (authContext.getOrgDN() != null && !authContext.getOrgDN().isEmpty()) {
        orgDN = authContext.getOrgDN();
        loginState.setQualifiedOrgDN(orgDN);
    } else {
        orgDN = loginState.getOrgDN();
    }
    clientType = loginState.getClientType();
    if (debug.messageEnabled()) {
        debug.message("orgDN : " + orgDN);
        debug.message("clientType : " + clientType);
    }
    /*
         * Throw an exception if module-based authentication is disabled and an authentication module other
         * than APPLICATION_MODULE or FEDERATION_MODULE is explicitly requested.
         */
    if (indexType == IndexType.MODULE_INSTANCE && !loginState.getEnableModuleBasedAuth() && !indexName.equals(ISAuthConstants.APPLICATION_MODULE)) {
        String moduleClassName = null;
        try {
            AMAuthenticationManager authManager = new AMAuthenticationManager(AccessController.doPrivileged(AdminTokenAction.getInstance()), orgDN);
            AMAuthenticationInstance authInstance = authManager.getAuthenticationInstance(indexName);
            moduleClassName = authInstance.getType();
        } catch (AMConfigurationException amce) {
            debug.error("AMLoginContext.executeLogin(): Unable to get authentication config", amce);
        }
        if (moduleClassName != null && !moduleClassName.equalsIgnoreCase(ISAuthConstants.FEDERATION_MODULE)) {
            throwExceptionIfModuleBasedAuthenticationDisabled();
        }
    }
    /*
         * Update LoginState indexType and indexName
         * (after storing current loginState indexType if required for HTTP callback processing)
         */
    IndexType prevIndexType = loginState.getIndexType();
    if (prevIndexType == IndexType.LEVEL || prevIndexType == IndexType.COMPOSITE_ADVICE) {
        loginState.setPreviousIndexType(prevIndexType);
    }
    loginState.setIndexType(indexType);
    loginState.setIndexName(indexName);
    /*
         * Delegate actual processing of requested authentication type to the dispatch method 'processIndexType'
         */
    try {
        if (processIndexType(indexType, indexName, orgDN)) {
            return;
        }
    } catch (AuthLoginException le) {
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        debug.message("Error  : ", le);
        throw le;
    } catch (Exception e) {
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        debug.message("Error : ", e);
        throw new AuthLoginException(e);
    }
    /*
         * Establish configName based on indexType, indexName, orgDN and clientType
         *
         * If configName can't be established, throw an exception
         */
    configName = getConfigName(indexType, indexName, orgDN, clientType);
    if (configName == null) {
        loginState.setErrorCode(AMAuthErrorCode.AUTH_CONFIG_NOT_FOUND);
        debug.message("Config not found");
        setErrorMsgAndTemplate();
        internalAuthError = true;
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        loginState.logFailed(bundle.getString("noConfig"), "NOCONFIG");
        auditor.auditLoginFailure(loginState, NO_CONFIG);
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_CONFIG_NOT_FOUND, null);
    }
    /*
         * Create the LoginContext object that actually handles login/logout
         */
    if (debug.messageEnabled()) {
        debug.message("Creating login context object\n" + "\n orgDN : " + orgDN + "\n configName : " + configName);
    }
    try {
        jaasCheck = AuthUtils.isPureJAASModulePresent(configName, this);
        if (isPureJAAS()) {
            debug.message("Using pure jaas mode.");
            if (authThread == null) {
                authThread = new AuthThreadManager();
                authThread.start();
            }
        }
        DSAMECallbackHandler dsameCallbackHandler = new DSAMECallbackHandler(this);
        if (isPureJAAS()) {
            if (subject != null) {
                loginContext = new javax.security.auth.login.LoginContext(configName, subject, dsameCallbackHandler);
            } else {
                loginContext = new javax.security.auth.login.LoginContext(configName, dsameCallbackHandler);
            }
        } else {
            debug.message("Using non pure jaas mode.");
            if (subject != null) {
                jaasLoginContext = new com.sun.identity.authentication.jaas.LoginContext(entries, subject, dsameCallbackHandler);
            } else {
                jaasLoginContext = new com.sun.identity.authentication.jaas.LoginContext(entries, dsameCallbackHandler);
            }
        }
    } catch (AuthLoginException ae) {
        debug.error("JAAS module for config: " + configName + ", " + ae.getMessage());
        if (debug.messageEnabled()) {
            debug.message("AuthLoginException", ae);
        }
        /* The user based authentication errors should not be different
             * for users who exist and who don't, which can lead to
             * possiblity of enumerating existing users.
             * The AMAuthErrorCode.AUTH_LOGIN_FAILED error code is used for
             * all user based authentication errors.
             * Refer issue3278
             */
        if (indexType == IndexType.USER && AMAuthErrorCode.AUTH_CONFIG_NOT_FOUND.equals(ae.getErrorCode())) {
            loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
        } else {
            loginState.setErrorCode(ae.getErrorCode());
        }
        setErrorMsgAndTemplate();
        loginState.logFailed(bundle.getString("loginContextCreateFailed"));
        auditor.auditLoginFailure(loginState);
        internalAuthError = true;
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        throw ae;
    } catch (LoginException le) {
        debug.error("in creating LoginContext.");
        if (debug.messageEnabled()) {
            debug.message("Exception ", le);
        }
        loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        loginState.logFailed(bundle.getString("loginContextCreateFailed"));
        auditor.auditLoginFailure(loginState);
        setErrorMsgAndTemplate();
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        internalAuthError = true;
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_ERROR, null, le);
    } catch (SecurityException se) {
        debug.error("security in creating LoginContext.");
        if (debug.messageEnabled()) {
            debug.message("Exception ", se);
        }
        loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        setErrorMsgAndTemplate();
        loginState.logFailed(bundle.getString("loginContextCreateFailed"));
        auditor.auditLoginFailure(loginState);
        internalAuthError = true;
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_ERROR, null);
    } catch (Exception e) {
        debug.error("Creating DSAMECallbackHandler: " + e.getMessage());
        loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        setErrorMsgAndTemplate();
        loginState.logFailed(bundle.getString("loginContextCreateFailed"));
        auditor.auditLoginFailure(loginState);
        internalAuthError = true;
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        loginStatus.setStatus(LoginStatus.AUTH_FAILED);
        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_ERROR, null, e);
    }
    /*
         * Perform the login using the objects this method has setup
         */
    try {
        if (isPureJAAS()) {
            if (jaasThread != null) {
                jaasThread.interrupt();
                jaasThread = null;
                errorState = true;
            } else {
                jaasThread = new JAASLoginThread(this);
                jaasThread.start();
            }
        } else {
            runLogin();
        }
    } catch (IllegalThreadStateException ite) {
        errorState = true;
    } catch (Exception e) {
        errorState = true;
    }
    if (errorState) {
        loginStatus.setStatus(LoginStatus.AUTH_RESET);
        loginState.setErrorCode(AMAuthErrorCode.AUTH_ERROR);
        setErrorMsgAndTemplate();
        internalAuthError = true;
        if (MonitoringUtil.isRunning()) {
            if (authImpl == null) {
                authImpl = Agent.getAuthSvcMBean();
            }
            if (authImpl != null) {
                authImpl.incSsoServerAuthenticationFailureCount();
            }
        }
        throw new AuthLoginException(BUNDLE_NAME, AMAuthErrorCode.AUTH_ERROR, null);
    }
    debug.message("AMLoginContext:Thread started... returning.");
}
Also used : AMConfigurationException(com.sun.identity.authentication.config.AMConfigurationException) IndexType(com.sun.identity.authentication.AuthContext.IndexType) AMAuthenticationManager(com.sun.identity.authentication.config.AMAuthenticationManager) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) LoginException(javax.security.auth.login.LoginException) MessageLoginException(com.sun.identity.authentication.spi.MessageLoginException) AuthErrorCodeException(com.sun.identity.authentication.spi.AuthErrorCodeException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) SSOException(com.iplanet.sso.SSOException) AMConfigurationException(com.sun.identity.authentication.config.AMConfigurationException) RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) Callback(javax.security.auth.callback.Callback) LoginException(javax.security.auth.login.LoginException) MessageLoginException(com.sun.identity.authentication.spi.MessageLoginException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) AMAuthenticationInstance(com.sun.identity.authentication.config.AMAuthenticationInstance)

Example 40 with AuthLoginException

use of com.sun.identity.authentication.spi.AuthLoginException in project OpenAM by OpenRock.

the class AMLoginContext method logout.

/**
     * Logs out.
     *
     * @throws AuthLoginException when fails to logout
     */
public void logout() throws AuthLoginException {
    debug.message("in logout:");
    try {
        if (isPureJAAS()) {
            if (loginContext != null) {
                loginContext.logout();
            }
        } else {
            if (jaasLoginContext != null) {
                jaasLoginContext.logout();
            }
        }
        loginState.logLogout();
        auditor.auditLogout(getSSOToken());
        loginState.postProcess(indexType, indexName, LoginState.PostProcessEvent.LOGOUT);
        destroySession();
        loginStatus.setStatus(LoginStatus.AUTH_COMPLETED);
    } catch (AuthLoginException le) {
        debug.message("Error during logout : ");
        if (debug.messageEnabled()) {
            debug.message("Exception ", le);
        }
        //logout - ignore this error since logout will be done
        throw new AuthLoginException(BUNDLE_NAME, "failedLogout", null, le);
    } catch (Exception e) {
        debug.message("Error during logout : ");
        if (debug.messageEnabled()) {
            debug.message("Exception ", e);
        }
    }
}
Also used : AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) LoginException(javax.security.auth.login.LoginException) MessageLoginException(com.sun.identity.authentication.spi.MessageLoginException) AuthErrorCodeException(com.sun.identity.authentication.spi.AuthErrorCodeException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) SSOException(com.iplanet.sso.SSOException) AMConfigurationException(com.sun.identity.authentication.config.AMConfigurationException)

Aggregations

AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)118 SSOException (com.iplanet.sso.SSOException)39 Callback (javax.security.auth.callback.Callback)29 IdRepoException (com.sun.identity.idm.IdRepoException)27 InvalidPasswordException (com.sun.identity.authentication.spi.InvalidPasswordException)25 NameCallback (javax.security.auth.callback.NameCallback)24 PasswordCallback (javax.security.auth.callback.PasswordCallback)23 IOException (java.io.IOException)20 Set (java.util.Set)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 SSOToken (com.iplanet.sso.SSOToken)14 HashMap (java.util.HashMap)14 AuthContext (com.sun.identity.authentication.AuthContext)13 Map (java.util.Map)12 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)12 Test (org.testng.annotations.Test)12 HashSet (java.util.HashSet)9 LoginException (javax.security.auth.login.LoginException)8 SSOTokenManager (com.iplanet.sso.SSOTokenManager)7 AuthException (com.sun.identity.authentication.service.AuthException)7