Search in sources :

Example 71 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class ThrottleConditionEvaluator method isThrottledWithinCondition.

private boolean isThrottledWithinCondition(MessageContext axis2MessageContext, AuthenticationContext authContext, List<ConditionDto> conditionDtoList) {
    ThrottleProperties throttleProperties = ServiceReferenceHolder.getInstance().getThrottleProperties();
    boolean status = true;
    for (ConditionDto condition : conditionDtoList) {
        status = true;
        if (condition.getIpCondition() != null) {
            if (!isMatchingIP(axis2MessageContext, condition.getIpCondition())) {
                status = false;
            }
        } else if (condition.getIpRangeCondition() != null) {
            if (!isWithinIP(axis2MessageContext, condition.getIpRangeCondition())) {
                status = false;
            }
        }
        if (condition.getHeaderConditions() != null && throttleProperties.isEnableHeaderConditions() && !condition.getHeaderConditions().getValues().isEmpty()) {
            if (!isHeaderPresent(axis2MessageContext, condition.getHeaderConditions())) {
                status = false;
            }
        }
        if (condition.getJwtClaimConditions() != null && throttleProperties.isEnableJwtConditions() && !condition.getJwtClaimConditions().getValues().isEmpty()) {
            if (!isJWTClaimPresent(authContext, condition.getJwtClaimConditions())) {
                status = false;
            }
        }
        if (condition.getQueryParameterConditions() != null && throttleProperties.isEnableQueryParamConditions() && !condition.getQueryParameterConditions().getValues().isEmpty()) {
            if (!isQueryParamPresent(axis2MessageContext, condition.getQueryParameterConditions())) {
                status = false;
            }
        }
        if (status) {
            break;
        }
    }
    return status;
}
Also used : ConditionDto(org.wso2.carbon.apimgt.impl.dto.ConditionDto) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)

Example 72 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class ThrottleConditionEvaluator method getApplicableConditions.

/**
 * When called, provides a list of Applicable Condition Groups for the current request.
 *
 * @param synapseContext        Message Context of the incoming request.
 * @param authenticationContext AuthenticationContext populated by {@code APIAuthenticationHandler}
 * @param inputConditionGroups  All Condition Groups Attached with the resource/API being invoked.
 * @return List of ConditionGroups applicable for the current request.
 */
public List<ConditionGroupDTO> getApplicableConditions(org.apache.synapse.MessageContext synapseContext, AuthenticationContext authenticationContext, ConditionGroupDTO[] inputConditionGroups) {
    ArrayList<ConditionGroupDTO> matchingConditions = new ArrayList<>(inputConditionGroups.length);
    ConditionGroupDTO defaultGroup = null;
    for (ConditionGroupDTO conditionGroup : inputConditionGroups) {
        if (APIConstants.THROTTLE_POLICY_DEFAULT.equals(conditionGroup.getConditionGroupId())) {
            defaultGroup = conditionGroup;
        } else if (isConditionGroupApplicable(synapseContext, authenticationContext, conditionGroup)) {
            matchingConditions.add(conditionGroup);
        }
    }
    // If no matching ConditionGroups are present, apply the default group.
    if (matchingConditions.isEmpty()) {
        matchingConditions.add(defaultGroup);
    }
    return matchingConditions;
}
Also used : ArrayList(java.util.ArrayList) ConditionGroupDTO(org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)

Example 73 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class APIThrottleHandler method doRoleBasedAccessThrottling.

private boolean doRoleBasedAccessThrottling(MessageContext synCtx, ConfigurationContext cc) {
    boolean canAccess = true;
    ThrottleDataHolder dataHolder = (ThrottleDataHolder) cc.getPropertyNonReplicable(ThrottleConstants.THROTTLE_INFO_KEY);
    if (throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY) == null) {
        // skip role base throttling
        return true;
    }
    ConcurrentAccessController cac = null;
    if (isClusteringEnable) {
        // for clustered  env.,gets it from axis configuration context
        cac = (ConcurrentAccessController) cc.getProperty(key);
    }
    if (!synCtx.isResponse()) {
        // gets the remote caller role name
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        String accessToken;
        String consumerKey;
        String authorizedUser;
        String roleID;
        String applicationId;
        String applicationTier;
        if (authContext != null) {
            // Although the method says getApiKey, what is actually returned is the Bearer header (accessToken)
            accessToken = authContext.getApiKey();
            consumerKey = authContext.getConsumerKey();
            authorizedUser = authContext.getUsername();
            roleID = authContext.getTier();
            applicationTier = authContext.getApplicationTier();
            applicationId = authContext.getApplicationId();
            if (accessToken == null || roleID == null) {
                log.warn("No consumer key or role information found on the request - " + "Throttling not applied");
                return true;
            }
        } else {
            log.warn("No authentication context information found on the request - " + "Throttling not applied");
            return true;
        }
        // Domain name based throttling
        // check whether a configuration has been defined for this role name or not
        // loads the ThrottleContext
        ThrottleContext resourceContext = throttle.getThrottleContext(RESOURCE_THROTTLE_KEY);
        if (resourceContext == null) {
            log.warn("Unable to load throttle context");
            return true;
        }
        // Loads the ThrottleConfiguration
        ThrottleConfiguration config = resourceContext.getThrottleConfiguration();
        if (config != null) {
            String applicationRoleId = null;
            // If an application level tier has been specified and it is not 'Unlimited'
            if (applicationTier != null && !APIConstants.UNLIMITED_TIER.equals(applicationTier)) {
                // Get the configuration role of the application
                // applicationRoleId = config.getConfigurationKeyOfCaller(applicationTier);
                applicationRoleId = applicationTier;
            }
            AccessInformation info = null;
            // If application level throttling is applied
            if (applicationRoleId != null) {
                ThrottleContext applicationThrottleContext = getApplicationThrottleContext(synCtx, dataHolder, applicationId);
                if (isClusteringEnable) {
                    applicationThrottleContext.setConfigurationContext(cc);
                    applicationThrottleContext.setThrottleId(id);
                }
                // First throttle by application
                try {
                    info = applicationRoleBasedAccessController.canAccess(applicationThrottleContext, applicationId, applicationRoleId);
                    if (log.isDebugEnabled()) {
                        log.debug("Throttle by Application " + applicationId);
                        log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
                    }
                } catch (ThrottleException e) {
                    log.warn("Exception occurred while performing role " + "based throttling", e);
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                    return false;
                }
                // check for the permission for access
                if (info != null && !info.isAccessAllowed()) {
                    log.info("Exceeded the allocated quota in Application level.");
                    // if the access has denied by rate based throttling
                    if (cac != null) {
                        cac.incrementAndGet();
                        // set back if this is a clustered env
                        if (isClusteringEnable) {
                            cc.setProperty(key, cac);
                            resourceContext.setConfigurationContext(cc);
                            // replicate the current state of ConcurrentAccessController
                            try {
                                Replicator.replicate(cc, new String[] { key });
                            } catch (ClusteringFault clusteringFault) {
                                log.error("Error during replicating states", clusteringFault);
                            }
                        }
                    }
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                    return false;
                }
            }
            // ---------------End of application level throttling------------
            // ==============================Start of Resource level throttling======================================
            // get throttling information for given request with resource path and http verb
            // VerbInfoDTO verbInfoDTO = null;
            // verbInfoDTO = validator.getVerbInfoDTOFromAPIData(apiContext, apiVersion, requestPath, httpMethod);
            VerbInfoDTO verbInfoDTO = (VerbInfoDTO) synCtx.getProperty(APIConstants.VERB_INFO_DTO);
            String resourceLevelRoleId = null;
            // no data related to verb information data
            if (verbInfoDTO == null) {
                log.warn("Error while getting throttling information for resource and http verb");
                return false;
            } else {
                // Not only we can proceed
                String resourceAndHTTPVerbThrottlingTier = verbInfoDTO.getThrottling();
                // If there no any tier then we need to set it as unlimited
                if (resourceAndHTTPVerbThrottlingTier == null) {
                    log.warn("Unable to find throttling information for resource and http verb. Throttling will " + "not apply");
                } else {
                    resourceLevelRoleId = resourceAndHTTPVerbThrottlingTier;
                }
                // adding consumerKey and authz_user combination instead of access token to resourceAndHTTPVerbKey
                // This avoids sending more than the permitted number of requests in a unit time by
                // regenerating the access token
                String resourceAndHTTPVerbKey = verbInfoDTO.getRequestKey() + '-' + consumerKey + ':' + authorizedUser;
                // if request not null then only we proceed
                if (resourceLevelRoleId != null) {
                    try {
                        // if application level throttling has passed
                        if (!APIConstants.UNLIMITED_TIER.equals(resourceLevelRoleId) && (info == null || info.isAccessAllowed())) {
                            // If this is a clustered env.
                            if (isClusteringEnable) {
                                resourceContext.setConfigurationContext(cc);
                                resourceContext.setThrottleId(id + "resource");
                            }
                            info = roleBasedAccessController.canAccess(resourceContext, resourceAndHTTPVerbKey, resourceAndHTTPVerbThrottlingTier);
                        }
                    } catch (ThrottleException e) {
                        log.warn("Exception occurred while performing resource" + "based throttling", e);
                        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                        return false;
                    }
                    // check for the permission for access
                    if (info != null && !info.isAccessAllowed()) {
                        log.info("Exceeded the allocated quota in Resource level.");
                        // if the access has denied by rate based throttling
                        if (cac != null) {
                            cac.incrementAndGet();
                            // set back if this is a clustered env
                            if (isClusteringEnable) {
                                cc.setProperty(key, cac);
                                // replicate the current state of ConcurrentAccessController
                                try {
                                    Replicator.replicate(cc, new String[] { key });
                                } catch (ClusteringFault clusteringFault) {
                                    log.error("Error during replicating states", clusteringFault);
                                }
                            }
                        }
                        if (isContinueOnThrottleReached(resourceAndHTTPVerbThrottlingTier)) {
                            // limit has reached.
                            if (synCtx.getProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY) == null) {
                                synCtx.setProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY, Boolean.TRUE);
                            }
                        } else {
                            synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                            return false;
                        }
                    }
                } else {
                    log.warn("Unable to find the throttle policy for role.");
                }
            }
            // ==============================End of Resource level throttling=======================================
            // ---------------Start of API level throttling------------------
            // Domain name based throttling
            // check whether a configuration has been defined for this role name or not
            // loads the ThrottleContext
            ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
            String apiKey;
            if (context == null) {
                log.warn("Unable to load throttle context");
                return true;
            }
            // If this is a clustered env.
            // check for configuration role of the caller
            config = context.getThrottleConfiguration();
            String consumerRoleID = config.getConfigurationKeyOfCaller(roleID);
            if (isClusteringEnable) {
                context.setConfigurationContext(cc);
                context.setThrottleId(id);
            }
            try {
                String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
                String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
                apiContext = apiContext != null ? apiContext : "";
                apiVersion = apiVersion != null ? apiVersion : "";
                // adding consumerKey and authz_user combination instead of access token to apiKey
                // This avoids sending more than the permitted number of requests in a unit time by
                // regenerating the access token
                apiKey = apiContext + ':' + apiVersion + ':' + consumerKey + ':' + authorizedUser;
                // if application level throttling has passed
                if (!APIConstants.UNLIMITED_TIER.equals(roleID) && (info == null || info.isAccessAllowed())) {
                    // Throttle by access token
                    info = roleBasedAccessController.canAccess(context, apiKey, consumerRoleID);
                }
            } catch (ThrottleException e) {
                log.warn("Exception occurred while performing role " + "based throttling", e);
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                return false;
            }
            // check for the permission for access
            if (info != null && !info.isAccessAllowed()) {
                log.info("Exceeded the allocated quota in API level.");
                // if the access has denied by rate based throttling
                if (cac != null) {
                    cac.incrementAndGet();
                    // set back if this is a clustered env
                    if (isClusteringEnable) {
                        cc.setProperty(key, cac);
                        // replicate the current state of ConcurrentAccessController
                        try {
                            Replicator.replicate(cc, new String[] { key });
                        } catch (ClusteringFault clusteringFault) {
                            log.error("Error during replicating states", clusteringFault);
                        }
                    }
                }
                if (isContinueOnThrottleReached(consumerRoleID)) {
                    // limit has reached.
                    if (synCtx.getProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY) == null) {
                        synCtx.setProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY, Boolean.TRUE);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Request throttled at API level for throttle key" + apiKey + ". But role " + consumerRoleID + "allows to continue to serve requests");
                    }
                } else {
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                    return false;
                }
            }
        }
    }
    // ---------------End of API level throttling------------------
    // ---------------Start of Hard throttling------------------
    ThrottleContext hardThrottleContext = throttle.getThrottleContext(APIThrottleConstants.HARD_THROTTLING_CONFIGURATION);
    try {
        String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
        String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
        apiContext = apiContext != null ? apiContext : "";
        apiVersion = apiVersion != null ? apiVersion : "";
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        if (hardThrottleContext != null && authContext.getKeyType() != null) {
            String throttleKey = apiContext + ':' + apiVersion + ':' + authContext.getKeyType();
            AccessInformation info = null;
            if (isClusteringEnable) {
                hardThrottleContext.setConfigurationContext(cc);
            }
            if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(authContext.getKeyType())) {
                hardThrottleContext.setThrottleId(id + APIThrottleConstants.PRODUCTION_HARD_LIMIT);
                info = roleBasedAccessController.canAccess(hardThrottleContext, throttleKey, APIThrottleConstants.PRODUCTION_HARD_LIMIT);
            } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(authContext.getKeyType())) {
                hardThrottleContext.setThrottleId(id + APIThrottleConstants.SANDBOX_HARD_LIMIT);
                info = roleBasedAccessController.canAccess(hardThrottleContext, throttleKey, APIThrottleConstants.SANDBOX_HARD_LIMIT);
            }
            if (log.isDebugEnabled()) {
                log.debug("Throttle by hard limit " + throttleKey);
                log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
            }
            if (info != null && !info.isAccessAllowed()) {
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
                log.info("Hard Throttling limit exceeded.");
                return false;
            }
        }
    } catch (ThrottleException e) {
        log.warn("Exception occurred while performing role based throttling", e);
        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
        return false;
    }
    return canAccess;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ThrottleDataHolder(org.apache.synapse.commons.throttle.core.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) ClusteringFault(org.apache.axis2.clustering.ClusteringFault)

Example 74 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class APIMOPARequestGenerator method generateRequest.

@Override
public String generateRequest(String policyName, String rule, Map<String, String> additionalParameters, MessageContext messageContext) throws OPASecurityException {
    JSONObject inputObject = new JSONObject();
    JSONObject opaPayload = new JSONObject();
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    TreeMap<String, String> transportHeadersMap = (TreeMap<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String requestOriginIP = OPAUtils.getRequestIp(axis2MessageContext);
    String requestMethod = (String) axis2MessageContext.getProperty(OPAConstants.HTTP_METHOD_STRING);
    String requestPath = (String) axis2MessageContext.getProperty(OPAConstants.API_BASEPATH_STRING);
    String electedResource = (String) axis2MessageContext.getProperty(ELECTED_RESOURCE_STRING);
    AuthenticationContext authContext = (AuthenticationContext) messageContext.getProperty("__API_AUTH_CONTEXT");
    if (authContext != null) {
        JSONObject apiContext = new JSONObject();
        apiContext.put("apiName", authContext.getApiName());
        apiContext.put("apiVersion", authContext.getApiVersion());
        apiContext.put("subscriberOrganization", authContext.getSubscriberTenantDomain());
        apiContext.put("isAuthenticated", authContext.isAuthenticated());
        apiContext.put("issuer", authContext.getIssuer());
        apiContext.put("apiPublisher", authContext.getApiPublisher());
        apiContext.put("keyType", authContext.getKeyType());
        apiContext.put("subscriber", authContext.getSubscriber());
        apiContext.put("consumerKey", authContext.getConsumerKey());
        apiContext.put("applicationUUID", authContext.getApplicationUUID());
        apiContext.put("applicationName", authContext.getApplicationName());
        apiContext.put("username", authContext.getUsername());
        if (additionalParameters.get("sendAccessToken") != null) {
            if (JavaUtils.isTrueExplicitly(additionalParameters.get("sendAccessToken"))) {
                apiContext.put("accessToken", authContext.getAccessToken());
            }
        }
        opaPayload.put("apiContext", apiContext);
    }
    opaPayload.put(OPAConstants.REQUEST_ORIGIN_KEY, requestOriginIP);
    opaPayload.put(OPAConstants.REQUEST_METHOD_KEY, requestMethod);
    opaPayload.put(OPAConstants.REQUEST_PATH_KEY, requestPath);
    opaPayload.put(OPAConstants.REQUEST_TRANSPORT_HEADERS_KEY, new JSONObject(transportHeadersMap));
    opaPayload.put("electedResource", electedResource);
    if (additionalParameters.get(OPAConstants.ADDITIONAL_MC_PROPERTY_PARAMETER) != null) {
        String additionalMCPropertiesString = additionalParameters.get(OPAConstants.ADDITIONAL_MC_PROPERTY_PARAMETER);
        String[] additionalMCProperties = additionalMCPropertiesString.split(OPAConstants.ADDITIONAL_MC_PROPERTY_DIVIDER);
        for (String mcProperty : additionalMCProperties) {
            if (messageContext.getProperty(mcProperty) != null) {
                opaPayload.put(mcProperty, messageContext.getProperty(mcProperty));
            }
        }
    }
    inputObject.put(OPAConstants.INPUT_KEY, opaPayload);
    return inputObject.toString();
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) JSONObject(org.json.JSONObject) TreeMap(java.util.TreeMap) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 75 with AuthenticationContext

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method publishSessionTermination.

/**
 * Overridden method which implements the access token revocation
 * @param request termination request
 * @param context termination context
 * @param sessionContext termination sessionContext
 * @param params termination params
 */
@Override
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    OAuthConsumerAppDTO[] appDTOs = new OAuthConsumerAppDTO[0];
    List<OAuthConsumerAppDTO> revokeAppList = new ArrayList<>();
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) params.get(user);
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    AuthenticatedUser federatedUser;
    SystemApplicationDTO[] systemApplicationDTOS = new SystemApplicationDTO[0];
    if (authenticatedUser.isFederatedUser()) {
        try {
            federatedUser = buildAuthenticatedUser(authenticatedUser);
            authenticatedUser = federatedUser;
        } catch (IdentityOAuth2Exception e) {
            log.error("Error thrown while building authenticated user in logout flow for user " + authenticatedUser.getUserName(), e);
        }
    }
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    try {
        appDTOs = getAppsAuthorizedByUser(authenticatedUser);
        if (appDTOs.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("The user: " + authenticatedUser.getUserName() + " has " + appDTOs.length + " OAuth apps");
            }
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error while retrieving applications authorized for the user " + authenticatedUser.getUserName(), e);
    }
    for (OAuthConsumerAppDTO appDTO : appDTOs) {
        for (SystemApplicationDTO systemApplicationDTO : systemApplicationDTOS) {
            if (StringUtils.equalsIgnoreCase(appDTO.getOauthConsumerKey(), systemApplicationDTO.getConsumerKey())) {
                revokeAppList.add(appDTO);
            }
        }
    }
    for (OAuthConsumerAppDTO appDTO : revokeAppList) {
        Set<AccessTokenDO> accessTokenDOs = null;
        try {
            // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this user
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), authenticatedUser, authenticatedUser.getUserStoreDomain(), true);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error while retrieving access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
        }
        AuthenticatedUser authzUser;
        if (accessTokenDOs != null) {
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                // Clear cache with AccessTokenDO
                authzUser = accessTokenDO.getAuthzUser();
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()), "NONE");
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
                Cache restApiTokenCache = CacheProvider.getRESTAPITokenCache();
                if (restApiTokenCache != null) {
                    restApiTokenCache.remove(accessTokenDO.getAccessToken());
                }
                AccessTokenDO scopedToken = null;
                try {
                    // Retrieve latest access token for particular client, user and scope combination if
                    // its ACTIVE or EXPIRED.
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), authenticatedUser, userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
                } catch (IdentityOAuth2Exception e) {
                    log.error("Error while retrieving scoped access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                }
                if (scopedToken != null) {
                    // Revoking token from database
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                    // Revoking the oauth consent from database.
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, username);
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                }
            }
        }
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) Cache(javax.cache.Cache)

Aggregations

AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)96 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)69 Test (org.junit.Test)69 MessageContext (org.apache.synapse.MessageContext)56 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)49 ArrayList (java.util.ArrayList)31 ConditionGroupDTO (org.wso2.carbon.apimgt.api.dto.ConditionGroupDTO)31 TreeMap (java.util.TreeMap)22 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)22 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)21 HashMap (java.util.HashMap)19 Cache (javax.cache.Cache)18 Test (org.testng.annotations.Test)18 AuthenticationContext (org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext)18 ThrottleProperties (org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)17 SignedJWT (com.nimbusds.jwt.SignedJWT)16 ConditionDTO (org.wso2.carbon.apimgt.api.dto.ConditionDTO)16 ThrottleDataHolder (org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder)16 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)15 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)14