Search in sources :

Example 56 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class CTSOperationsTest method shouldThrowExceptionOnReadError.

@Test(expectedExceptions = SessionException.class)
public void shouldThrowExceptionOnReadError() throws CoreTokenException, SessionException {
    // Given
    given(mockCTS.read(anyString())).willThrow(new CoreTokenException(""));
    // When / Then Throw
    ctsOperations.refresh(mockSession, false);
}
Also used : CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) Test(org.testng.annotations.Test)

Example 57 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class OAuth method process.

public int process(Callback[] callbacks, int state) throws LoginException {
    OAuthUtil.debugMessage("process: state = " + state);
    HttpServletRequest request = getHttpServletRequest();
    HttpServletResponse response = getHttpServletResponse();
    if (request == null) {
        OAuthUtil.debugError("OAuth.process(): The request was null, this is " + "an interactive module");
        return ISAuthConstants.LOGIN_IGNORE;
    }
    // We are being redirected back from an OAuth 2 Identity Provider
    String code = request.getParameter(PARAM_CODE);
    if (code != null) {
        OAuthUtil.debugMessage("OAuth.process(): GOT CODE: " + code);
        state = GET_OAUTH_TOKEN_STATE;
    }
    // The Proxy is used to return with a POST to the module
    proxyURL = config.getProxyURL();
    switch(state) {
        case ISAuthConstants.LOGIN_START:
            {
                config.validateConfiguration();
                serverName = request.getServerName();
                StringBuilder originalUrl = new StringBuilder();
                String requestedQuery = request.getQueryString();
                String realm = null;
                String authCookieName = AuthUtils.getAuthCookieName();
                final XUIState xuiState = InjectorHolder.getInstance(XUIState.class);
                if (xuiState.isXUIEnabled()) {
                    // When XUI is in use the request URI points to the authenticate REST endpoint, which shouldn't be
                    // presented to the end-user, hence we use the contextpath only and rely on index.html and the
                    // XUIFilter to direct the user towards the XUI.
                    originalUrl.append(request.getContextPath());
                    // the realm parameter was not present on the querystring, then we add it there.
                    if (requestedQuery != null && !requestedQuery.contains("realm=")) {
                        realm = request.getParameter("realm");
                    }
                } else {
                    //In case of legacy UI the request URI will be /openam/UI/Login, which is safe to use.
                    originalUrl.append(request.getRequestURI());
                }
                if (StringUtils.isNotEmpty(realm)) {
                    originalUrl.append("?realm=").append(URLEncDec.encode(realm));
                }
                if (requestedQuery != null) {
                    if (requestedQuery.endsWith(authCookieName + "=")) {
                        requestedQuery = requestedQuery.substring(0, requestedQuery.length() - authCookieName.length() - 1);
                    }
                    originalUrl.append(originalUrl.indexOf("?") == -1 ? '?' : '&');
                    originalUrl.append(requestedQuery);
                }
                // Find the domains for which we are configured
                Set<String> domains = AuthClientUtils.getCookieDomainsForRequest(request);
                String ProviderLogoutURL = config.getLogoutServiceUrl();
                String csrfStateTokenId = RandomStringUtils.randomAlphanumeric(32);
                String csrfState = createAuthorizationState();
                Token csrfStateToken = new Token(csrfStateTokenId, TokenType.GENERIC);
                csrfStateToken.setAttribute(CoreTokenField.STRING_ONE, csrfState);
                try {
                    ctsStore.create(csrfStateToken);
                } catch (CoreTokenException e) {
                    OAuthUtil.debugError("OAuth.process(): Authorization redirect failed to be sent because the state " + "could not be stored");
                    throw new AuthLoginException("OAuth.process(): Authorization redirect failed to be sent because " + "the state could not be stored", e);
                }
                // when retrieving the token
                for (String domain : domains) {
                    CookieUtils.addCookieToResponse(response, CookieUtils.newCookie(COOKIE_PROXY_URL, proxyURL, "/", domain));
                    CookieUtils.addCookieToResponse(response, CookieUtils.newCookie(COOKIE_ORIG_URL, originalUrl.toString(), "/", domain));
                    CookieUtils.addCookieToResponse(response, CookieUtils.newCookie(NONCE_TOKEN_ID, csrfStateTokenId, "/", domain));
                    if (ProviderLogoutURL != null && !ProviderLogoutURL.isEmpty()) {
                        CookieUtils.addCookieToResponse(response, CookieUtils.newCookie(COOKIE_LOGOUT_URL, ProviderLogoutURL, "/", domain));
                    }
                }
                // The Proxy is used to return with a POST to the module
                setUserSessionProperty(ISAuthConstants.FULL_LOGIN_URL, originalUrl.toString());
                setUserSessionProperty(SESSION_LOGOUT_BEHAVIOUR, config.getLogoutBhaviour());
                String authServiceUrl = config.getAuthServiceUrl(proxyURL, csrfState);
                OAuthUtil.debugMessage("OAuth.process(): New RedirectURL=" + authServiceUrl);
                Callback[] callbacks1 = getCallback(2);
                RedirectCallback rc = (RedirectCallback) callbacks1[0];
                RedirectCallback rcNew = new RedirectCallback(authServiceUrl, null, "GET", rc.getStatusParameter(), rc.getRedirectBackUrlCookieName());
                rcNew.setTrackingCookie(true);
                replaceCallback(2, 0, rcNew);
                return GET_OAUTH_TOKEN_STATE;
            }
        case GET_OAUTH_TOKEN_STATE:
            {
                final String csrfState;
                if (request.getParameter("jsonContent") != null) {
                    final JsonValue jval = JsonValueBuilder.toJsonValue(request.getParameter("jsonContent"));
                    csrfState = jval.get("state").asString();
                    code = jval.get(PARAM_CODE).asString();
                } else {
                    csrfState = request.getParameter("state");
                    code = request.getParameter(PARAM_CODE);
                }
                if (csrfState == null) {
                    OAuthUtil.debugError("OAuth.process(): Authorization call-back failed because there was no state " + "parameter");
                    throw new AuthLoginException(BUNDLE_NAME, "noState", null);
                }
                try {
                    Token csrfStateToken = ctsStore.read(OAuthUtil.findCookie(request, NONCE_TOKEN_ID));
                    ctsStore.deleteAsync(csrfStateToken);
                    String expectedCsrfState = csrfStateToken.getValue(CoreTokenField.STRING_ONE);
                    if (!expectedCsrfState.equals(csrfState)) {
                        OAuthUtil.debugError("OAuth.process(): Authorization call-back failed because the state parameter " + "contained an unexpected value");
                        throw new AuthLoginException(BUNDLE_NAME, "incorrectState", null);
                    }
                    // We are being redirected back from an OAuth 2 Identity Provider
                    if (code == null || code.isEmpty()) {
                        OAuthUtil.debugMessage("OAuth.process(): LOGIN_IGNORE");
                        return ISAuthConstants.LOGIN_START;
                    }
                    validateInput("code", code, "HTTPParameterValue", 2000, false);
                    OAuthUtil.debugMessage("OAuth.process(): code parameter: " + code);
                    String tokenSvcResponse = getContent(config.getTokenServiceUrl(code, proxyURL), null);
                    OAuthUtil.debugMessage("OAuth.process(): token=" + tokenSvcResponse);
                    JwtClaimsSet jwtClaims = null;
                    String idToken = null;
                    if (config.isOpenIDConnect()) {
                        idToken = extractToken(ID_TOKEN, tokenSvcResponse);
                        JwtHandler jwtHandler = new JwtHandler(jwtHandlerConfig);
                        try {
                            jwtClaims = jwtHandler.validateJwt(idToken);
                        } catch (RuntimeException | AuthLoginException e) {
                            debug.warning("Cannot validate JWT", e);
                            throw e;
                        }
                        if (!JwtHandler.isIntendedForAudience(config.getClientId(), jwtClaims)) {
                            OAuthUtil.debugError("OAuth.process(): ID token is not for this client as audience.");
                            throw new AuthLoginException(BUNDLE_NAME, "audience", null);
                        }
                    }
                    String token = extractToken(PARAM_ACCESS_TOKEN, tokenSvcResponse);
                    setUserSessionProperty(SESSION_OAUTH_TOKEN, token);
                    String profileSvcResponse = null;
                    if (StringUtils.isNotEmpty(config.getProfileServiceUrl())) {
                        profileSvcResponse = getContent(config.getProfileServiceUrl(), "Bearer " + token);
                        OAuthUtil.debugMessage("OAuth.process(): Profile Svc response: " + profileSvcResponse);
                    }
                    String realm = getRequestOrg();
                    if (realm == null) {
                        realm = "/";
                    }
                    AccountProvider accountProvider = instantiateAccountProvider();
                    AttributeMapper accountAttributeMapper = instantiateAccountMapper();
                    Map<String, Set<String>> userNames = getAttributes(profileSvcResponse, config.getAccountMapperConfig(), accountAttributeMapper, jwtClaims);
                    String user = null;
                    if (!userNames.isEmpty()) {
                        user = getUser(realm, accountProvider, userNames);
                    }
                    if (user == null && !config.getCreateAccountFlag()) {
                        authenticatedUser = getDynamicUser(userNames);
                        if (authenticatedUser != null) {
                            if (config.getSaveAttributesToSessionFlag()) {
                                Map<String, Set<String>> attributes = getAttributesMap(profileSvcResponse, jwtClaims);
                                saveAttributes(attributes);
                            }
                            OAuthUtil.debugMessage("OAuth.process(): LOGIN_SUCCEED " + "with user " + authenticatedUser);
                            storeUsernamePasswd(authenticatedUser, null);
                            return ISAuthConstants.LOGIN_SUCCEED;
                        } else {
                            throw new AuthLoginException("No user mapped!");
                        }
                    }
                    if (user == null && config.getCreateAccountFlag()) {
                        if (config.getPromptPasswordFlag()) {
                            setUserSessionProperty(PROFILE_SERVICE_RESPONSE, profileSvcResponse);
                            if (config.isOpenIDConnect()) {
                                setUserSessionProperty(OPENID_TOKEN, idToken);
                            }
                            return SET_PASSWORD_STATE;
                        } else {
                            authenticatedUser = provisionAccountNow(accountProvider, realm, profileSvcResponse, getRandomData(), jwtClaims);
                            if (authenticatedUser != null) {
                                OAuthUtil.debugMessage("User created: " + authenticatedUser);
                                storeUsernamePasswd(authenticatedUser, null);
                                return ISAuthConstants.LOGIN_SUCCEED;
                            } else {
                                return ISAuthConstants.LOGIN_IGNORE;
                            }
                        }
                    }
                    if (user != null) {
                        authenticatedUser = user;
                        OAuthUtil.debugMessage("OAuth.process(): LOGIN_SUCCEED " + "with user " + authenticatedUser);
                        if (config.getSaveAttributesToSessionFlag()) {
                            Map<String, Set<String>> attributes = getAttributesMap(profileSvcResponse, jwtClaims);
                            saveAttributes(attributes);
                        }
                        storeUsernamePasswd(authenticatedUser, null);
                        return ISAuthConstants.LOGIN_SUCCEED;
                    }
                } catch (JSONException je) {
                    OAuthUtil.debugError("OAuth.process(): JSONException: " + je.getMessage());
                    throw new AuthLoginException(BUNDLE_NAME, "json", null, je);
                } catch (SSOException ssoe) {
                    OAuthUtil.debugError("OAuth.process(): SSOException: " + ssoe.getMessage());
                    throw new AuthLoginException(BUNDLE_NAME, "ssoe", null, ssoe);
                } catch (IdRepoException ire) {
                    OAuthUtil.debugError("OAuth.process(): IdRepoException: " + ire.getMessage());
                    throw new AuthLoginException(BUNDLE_NAME, "ire", null, ire);
                } catch (CoreTokenException e) {
                    OAuthUtil.debugError("OAuth.process(): Authorization call-back failed because the state parameter " + "contained an unexpected value");
                    throw new AuthLoginException(BUNDLE_NAME, "incorrectState", null, e);
                }
                break;
            }
        case SET_PASSWORD_STATE:
            {
                if (!config.getCreateAccountFlag()) {
                    return ISAuthConstants.LOGIN_IGNORE;
                }
                userPassword = request.getParameter(PARAM_TOKEN1);
                validateInput(PARAM_TOKEN1, userPassword, "HTTPParameterValue", 512, false);
                String userPassword2 = request.getParameter(PARAM_TOKEN2);
                validateInput(PARAM_TOKEN2, userPassword2, "HTTPParameterValue", 512, false);
                if (!userPassword.equals(userPassword2)) {
                    OAuthUtil.debugWarning("OAuth.process(): Passwords did not match!");
                    return SET_PASSWORD_STATE;
                }
                String terms = request.getParameter("terms");
                if (!terms.equalsIgnoreCase("accept")) {
                    return SET_PASSWORD_STATE;
                }
                String profileSvcResponse = getUserSessionProperty("ATTRIBUTES");
                data = getRandomData();
                String mail = getMail(profileSvcResponse, config.getMailAttribute());
                OAuthUtil.debugMessage("Mail found = " + mail);
                try {
                    OAuthUtil.sendEmail(config.getEmailFrom(), mail, data, config.getSMTPConfig(), bundle, proxyURL);
                } catch (NoEmailSentException ex) {
                    OAuthUtil.debugError("No mail sent due to error", ex);
                    throw new AuthLoginException("Aborting authentication, because " + "the mail could not be sent due to a mail sending error");
                }
                OAuthUtil.debugMessage("User to be created, we need to activate: " + data);
                return CREATE_USER_STATE;
            }
        case CREATE_USER_STATE:
            {
                String activation = request.getParameter(PARAM_ACTIVATION);
                validateInput(PARAM_ACTIVATION, activation, "HTTPParameterValue", 512, false);
                OAuthUtil.debugMessage("code entered by the user: " + activation);
                if (activation == null || activation.isEmpty() || !activation.trim().equals(data.trim())) {
                    return CREATE_USER_STATE;
                }
                String profileSvcResponse = getUserSessionProperty(PROFILE_SERVICE_RESPONSE);
                String idToken = getUserSessionProperty(ID_TOKEN);
                String realm = getRequestOrg();
                if (realm == null) {
                    realm = "/";
                }
                OAuthUtil.debugMessage("Got Attributes: " + profileSvcResponse);
                AccountProvider accountProvider = instantiateAccountProvider();
                JwtClaimsSet jwtClaims = null;
                if (idToken != null) {
                    jwtClaims = new JwtHandler(jwtHandlerConfig).getJwtClaims(idToken);
                }
                authenticatedUser = provisionAccountNow(accountProvider, realm, profileSvcResponse, userPassword, jwtClaims);
                if (authenticatedUser != null) {
                    OAuthUtil.debugMessage("User created: " + authenticatedUser);
                    storeUsernamePasswd(authenticatedUser, null);
                    return ISAuthConstants.LOGIN_SUCCEED;
                } else {
                    return ISAuthConstants.LOGIN_IGNORE;
                }
            }
        default:
            {
                OAuthUtil.debugError("OAuth.process(): Illegal State");
                return ISAuthConstants.LOGIN_IGNORE;
            }
    }
    throw new AuthLoginException(BUNDLE_NAME, "unknownState", null);
}
Also used : RedirectCallback(com.sun.identity.authentication.spi.RedirectCallback) Set(java.util.Set) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) JSONException(org.json.JSONException) Token(org.forgerock.openam.cts.api.tokens.Token) SSOException(com.iplanet.sso.SSOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) AttributeMapper(org.forgerock.openam.authentication.modules.common.mapping.AttributeMapper) JwtHandler(org.forgerock.openam.authentication.modules.oidc.JwtHandler) XUIState(org.forgerock.openam.xui.XUIState) AccountProvider(org.forgerock.openam.authentication.modules.common.mapping.AccountProvider) Map(java.util.Map) HashMap(java.util.HashMap)

Example 58 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class CoreTokenResource method createInstance.

/**
     * Create a token in the store.
     *
     * This call expects a JSON serialised Token instance to be passed in via the CreateRequest.
     *
     * @param serverContext Required context.
     * @param createRequest Contains the serialised JSON value of the Token.
     */
public Promise<ResourceResponse, ResourceException> createInstance(Context serverContext, CreateRequest createRequest) {
    String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext);
    String json = createRequest.getContent().toString();
    Token token = serialisation.deserialise(json, Token.class);
    try {
        store.createAsync(token);
        Map<String, String> result = new HashMap<String, String>();
        result.put(TOKEN_ID, token.getTokenId());
        ResourceResponse resource = newResourceResponse(token.getTokenId(), String.valueOf(System.currentTimeMillis()), new JsonValue(result));
        debug("CREATE by {0}: Stored token with ID: {1}", principal, token.getTokenId());
        return newResultPromise(resource);
    } catch (IllegalArgumentException e) {
        return new BadRequestException(e.getMessage()).asPromise();
    } catch (CoreTokenException e) {
        error(e, "CREATE by {0}: Error creating token resource with ID: {1}", principal, token.getTokenId());
        return generateException(e).asPromise();
    }
}
Also used : Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) Token(org.forgerock.openam.cts.api.tokens.Token)

Example 59 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class SessionService method recoverSession.

/**
     * If InternalSession is not present, we attempt to recover its state from
     * associated HttpSession. We have to set the session tracking cookie to
     * HttpID which is present in the SessionID object. This will work in the
     * fail over cases. We first get the HttpSession by invoking the
     * GetHttpSession Servlet on the SAME server instance this code is invoked.
     * This should trigger the Web container to perform recovery of the
     * associated Http session
     * <p/>
     * We also pass the SessionID to the servlet to double check the match
     * between the session id and Http session
     * <p/>
     * This is the "client side" of the remote invocation. The servlet will call
     * retrieveSession() to complete the work
     *
     * @param sid Session ID
     */
InternalSession recoverSession(SessionID sid) {
    if (!serviceConfig.isSessionFailoverEnabled()) {
        return null;
    }
    InternalSession sess = null;
    if (serviceConfig.isUseInternalRequestRoutingEnabled()) {
        try {
            String tokenId = tokenIdFactory.toSessionTokenId(sid);
            Token token = getRepository().read(tokenId);
            if (token == null) {
                return sess;
            }
            /**
                 * As a side effect of deserialising an InternalSession, we must trigger
                 * the InternalSession to reschedule its timing task to ensure it
                 * maintains the session expiry function.
                 */
            sess = tokenAdapter.fromToken(token);
            sess.setSessionServiceDependencies(this, serviceConfig, sessionLogging, sessionAuditor, sessionCookies, sessionDebug);
            sess.scheduleExpiry();
            updateSessionMaps(sess);
        } catch (CoreTokenException e) {
            sessionDebug.error("Failed to retrieve new session", e);
        }
    } else {
        if (sessionDebug.messageEnabled()) {
            sessionDebug.message("Recovering InternalSession from HttpSession: " + sid);
        }
        DataInputStream in = null;
        try {
            String query = "?" + GetHttpSession.OP + "=" + GetHttpSession.RECOVER_OP;
            URL url = serverConfig.createLocalServerURL("GetHttpSession" + query);
            HttpURLConnection conn = httpConnectionFactory.createSessionAwareConnection(url, sid, null);
            in = new DataInputStream(conn.getInputStream());
            sess = cache.getBySessionID(sid);
            if (sess == null) {
                sess = resolveRestrictedToken(sid, false);
            }
        } catch (Exception ex) {
            sessionDebug.error("Failed to retrieve new session", ex);
        } finally {
            IOUtils.closeIfNotNull(in);
        }
    }
    return sess;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) SSOToken(com.iplanet.sso.SSOToken) Token(org.forgerock.openam.cts.api.tokens.Token) DataInputStream(java.io.DataInputStream) URL(java.net.URL) DelegationException(com.sun.identity.delegation.DelegationException) SSOException(com.iplanet.sso.SSOException) InterruptedIOException(java.io.InterruptedIOException) IdRepoException(com.sun.identity.idm.IdRepoException) ConnectException(java.net.ConnectException) SessionException(com.iplanet.dpro.session.SessionException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException)

Aggregations

CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)59 JsonValue (org.forgerock.json.JsonValue)21 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)19 Token (org.forgerock.openam.cts.api.tokens.Token)14 Test (org.testng.annotations.Test)11 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)10 ResourceException (org.forgerock.json.resource.ResourceException)9 PartialToken (org.forgerock.openam.sm.datalayer.api.query.PartialToken)9 BadRequestException (org.forgerock.json.resource.BadRequestException)8 ArrayList (java.util.ArrayList)7 ResourceResponse (org.forgerock.json.resource.ResourceResponse)7 SSOException (com.iplanet.sso.SSOException)6 SSOToken (com.iplanet.sso.SSOToken)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 HashMap (java.util.HashMap)5 Responses.newResourceResponse (org.forgerock.json.resource.Responses.newResourceResponse)5 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)5 TokenFilter (org.forgerock.openam.cts.api.filter.TokenFilter)5 TokenFilterBuilder (org.forgerock.openam.cts.api.filter.TokenFilterBuilder)5 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)5