Search in sources :

Example 1 with Pair

use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.

the class ApiMgtDAO method getConsumerKeysForApplication.

/**
 * Retrieves the consumer keys and keymanager in a given application
 *
 * @param appId application id
 * @return Map<ConsumerKey, Pair<keyManagerName, keyManagerTenantDomain>
 * @throws APIManagementException
 */
public Map<String, Pair<String, String>> getConsumerKeysForApplication(int appId) throws APIManagementException {
    Map<String, Pair<String, String>> consumerKeysOfApplication = new HashMap<>();
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(SQLConstants.GET_CONSUMER_KEY_OF_APPLICATION_SQL)) {
        preparedStatement.setInt(1, appId);
        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                String consumerKey = resultSet.getString("CONSUMER_KEY");
                String keyManagerName = resultSet.getString("NAME");
                String keyManagerOrganization = resultSet.getString("ORGANIZATION");
                consumerKeysOfApplication.put(consumerKey, Pair.of(keyManagerName, keyManagerOrganization));
            }
        }
    } catch (SQLException e) {
        String msg = "Error occurred while getting consumer keys for application " + appId;
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return consumerKeysOfApplication;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Pair(org.apache.commons.lang3.tuple.Pair)

Example 2 with Pair

use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.

the class APIAuthenticationHandler method isAuthenticate.

/**
 * Authenticates the given request using the authenticators which have been initialized.
 *
 * @param messageContext The message to be authenticated
 * @return true if the authentication is successful (never returns false)
 * @throws APISecurityException If an authentication failure or some other error occurs
 */
protected boolean isAuthenticate(MessageContext messageContext) throws APISecurityException, APIManagementException {
    boolean authenticated = false;
    AuthenticationResponse authenticationResponse;
    List<AuthenticationResponse> authResponses = new ArrayList<>();
    for (Authenticator authenticator : authenticators) {
        authenticationResponse = authenticator.authenticate(messageContext);
        if (authenticationResponse.isMandatoryAuthentication()) {
            // Update authentication status only if the authentication is a mandatory one
            authenticated = authenticationResponse.isAuthenticated();
        }
        if (!authenticationResponse.isAuthenticated()) {
            authResponses.add(authenticationResponse);
        }
        if (!authenticationResponse.isContinueToNextAuthenticator()) {
            break;
        }
    }
    if (!authenticated) {
        Pair<Integer, String> error = getError(authResponses);
        throw new APISecurityException(error.getKey(), error.getValue());
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) OAuthAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator) BasicAuthAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.basicauth.BasicAuthAuthenticator) InternalAPIKeyAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.InternalAPIKeyAuthenticator) MutualSSLAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.MutualSSLAuthenticator) ApiKeyAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.apikey.ApiKeyAuthenticator)

Example 3 with Pair

use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.

the class SystemScopesIssuer method validateScope.

@Override
public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws IdentityOAuth2Exception {
    AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
    if (accessTokenDO == null) {
        return false;
    }
    String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
    // Return true if there is no resource to validate the token against.
    if (resource == null) {
        return true;
    }
    // Get the list of scopes associated with the access token
    String[] scopes = accessTokenDO.getScope();
    // If no scopes are associated with the token
    if (scopes == null || scopes.length == 0) {
        return true;
    }
    String resourceScope = null;
    int resourceTenantId = -1;
    boolean cacheHit = false;
    // Check the cache, if caching is enabled.
    OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
    CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);
    // Cache hit
    if (result != null && result instanceof ResourceScopeCacheEntry) {
        resourceScope = ((ResourceScopeCacheEntry) result).getScope();
        resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
        cacheHit = true;
    }
    // Cache was not hit. So retrieve from database.
    if (!cacheHit) {
        Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().findTenantAndScopeOfResource(resource);
        if (scopeMap != null) {
            resourceScope = scopeMap.getLeft();
            resourceTenantId = scopeMap.getRight();
        }
        cacheKey = new OAuthCacheKey(resource);
        ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
        cacheEntry.setTenantId(resourceTenantId);
        // Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
        // which scopes haven't been defined).
        OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
    }
    // Return TRUE if - There does not exist a scope definition for the resource
    if (resourceScope == null) {
        if (log.isDebugEnabled()) {
            log.debug("Resource '" + resource + "' is not protected with a scope");
        }
        return true;
    }
    List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));
    // If the access token does not bear the scope required for accessing the Resource.
    if (!scopeList.contains(resourceScope)) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" + resourceScope + "'");
        }
        return false;
    }
    // This system property is set at server start using -D option, Thus will be a permanent property.
    if (accessTokenDO.getAuthzUser().isFederatedUser() && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) || !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
        return true;
    }
    AuthenticatedUser authenticatedUser = OAuthUtil.getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
    String clientId = accessTokenDO.getConsumerKey();
    List<String> requestedScopes = Arrays.asList(scopes);
    List<String> authorizedScopes = null;
    String[] userRoles = null;
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            authorizedScopes = getAllowedScopes(requestedScopes);
            oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
            return true;
        }
        userRoles = getUserRoles(authenticatedUser);
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
    }
    if (ArrayUtils.isEmpty(userRoles)) {
        if (log.isDebugEnabled()) {
            log.debug("No roles associated for the user " + authenticatedUser.getUserName());
        }
        return false;
    }
    return true;
}
Also used : ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry) CacheEntry(org.wso2.carbon.identity.oauth.cache.CacheEntry) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry)

Example 4 with Pair

use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.

the class RegistrationServiceImpl method fromAppDTOToApplicationInfo.

/**
 * Creating a OAuthApplicationInfo type object to return
 *
 * @param clientId     client id
 * @param clientName   client name
 * @param callbackUrl  callback url
 * @param clientSecret clientSecret
 * @param saasApp      IsSaasApp
 * @param appOwner     AppOwner
 * @param sampleMap    Map
 * @return OAuthApplicationInfo object containing parsed values.
 */
private OAuthApplicationInfo fromAppDTOToApplicationInfo(String clientId, String clientName, String callbackUrl, String clientSecret, boolean saasApp, String appOwner, Map<String, String> sampleMap) {
    OAuthApplicationInfo updatingApp = new OAuthApplicationInfo();
    updatingApp.setClientId(clientId);
    updatingApp.setClientName(clientName);
    updatingApp.setCallBackURL(callbackUrl);
    updatingApp.setClientSecret(clientSecret);
    updatingApp.setIsSaasApplication(saasApp);
    updatingApp.setAppOwner(appOwner);
    Iterator it = sampleMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        updatingApp.addParameter((String) pair.getKey(), pair.getValue());
        it.remove();
    }
    return updatingApp;
}
Also used : OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Iterator(java.util.Iterator) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with Pair

use of org.wso2.carbon.identity.mgt.endpoint.util.client.Pair in project carbon-apimgt by wso2.

the class PolicyUtil method deployPolicy.

/**
 * Deploy the given throttle policy in the Traffic Manager.
 *
 * @param policy      policy object
 * @param policyEvent policy event object which was triggered
 */
public static void deployPolicy(Policy policy, PolicyEvent policyEvent) {
    EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
    ThrottlePolicyTemplateBuilder policyTemplateBuilder = new ThrottlePolicyTemplateBuilder();
    Map<String, String> policiesToDeploy = new HashMap<>();
    List<String> policiesToUndeploy = new ArrayList<>();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
        String policyFile;
        String policyString;
        if (Policy.PolicyType.SUBSCRIPTION.equals(policy.getType()) && policy instanceof SubscriptionPolicy) {
            // Add Subscription policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_SUB, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForSubscriptionLevel((SubscriptionPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.APPLICATION.equals(policy.getType()) && policy instanceof ApplicationPolicy) {
            // Add Application policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_APP, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForAppLevel((ApplicationPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.API.equals(policy.getType()) && policy instanceof ApiPolicy) {
            // Add API policy
            policiesToDeploy = policyTemplateBuilder.getThrottlePolicyForAPILevel((ApiPolicy) policy);
            String defaultPolicy = policyTemplateBuilder.getThrottlePolicyForAPILevelDefault((ApiPolicy) policy);
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_RESOURCE, policy.getName());
            String defaultPolicyName = policyFile + APIConstants.THROTTLE_POLICY_DEFAULT;
            policiesToDeploy.put(defaultPolicyName, defaultPolicy);
            if (policyEvent instanceof APIPolicyEvent) {
                List<Integer> deletedConditionGroupIds = ((APIPolicyEvent) policyEvent).getDeletedConditionGroupIds();
                // Undeploy removed condition groups
                if (deletedConditionGroupIds != null) {
                    for (int conditionGroupId : deletedConditionGroupIds) {
                        policiesToUndeploy.add(policyFile + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroupId);
                    }
                }
            }
        } else if (Policy.PolicyType.GLOBAL.equals(policy.getType()) && policy instanceof GlobalPolicy) {
            // Add Global policy
            GlobalPolicy globalPolicy = (GlobalPolicy) policy;
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, PolicyConstants.POLICY_LEVEL_GLOBAL, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForGlobalLevel(globalPolicy);
            policiesToDeploy.put(policyFile, policyString);
        }
        // Undeploy removed policies
        undeployPolicies(policiesToUndeploy);
        for (Map.Entry<String, String> pair : policiesToDeploy.entrySet()) {
            String policyPlanName = pair.getKey();
            String flowString = pair.getValue();
            String executionPlan = null;
            try {
                executionPlan = eventProcessorService.getActiveExecutionPlan(policyPlanName);
            } catch (ExecutionPlanConfigurationException e) {
                // Deploy new policies
                eventProcessorService.deployExecutionPlan(flowString);
            }
            if (executionPlan != null) {
                // Update existing policies
                eventProcessorService.editActiveExecutionPlan(flowString, policyPlanName);
            }
        }
    } catch (APITemplateException e) {
        log.error("Error in creating execution plan", e);
    } catch (ExecutionPlanConfigurationException | ExecutionPlanDependencyValidationException e) {
        log.error("Error in deploying execution plan", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : HashMap(java.util.HashMap) GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) ArrayList(java.util.ArrayList) ApiPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy) ExecutionPlanConfigurationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanConfigurationException) EventProcessorService(org.wso2.carbon.event.processor.core.EventProcessorService) ExecutionPlanDependencyValidationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanDependencyValidationException) SubscriptionPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.SubscriptionPolicy) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) ApplicationPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

HashMap (java.util.HashMap)17 ArrayList (java.util.ArrayList)14 Map (java.util.Map)8 ApiException (org.wso2.carbon.identity.mgt.endpoint.util.client.ApiException)6 Pair (org.wso2.carbon.identity.mgt.endpoint.util.client.Pair)6 Property (org.wso2.carbon.identity.mgt.endpoint.util.client.model.Property)6 GenericType (com.sun.jersey.api.client.GenericType)4 Iterator (java.util.Iterator)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 OAuthConsumerDAO (org.wso2.carbon.identity.oauth.dao.OAuthConsumerDAO)3 GoogleOAuthParameters (com.google.gdata.client.authn.oauth.GoogleOAuthParameters)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 Collection (java.util.Collection)2 List (java.util.List)2 OMElement (org.apache.axiom.om.OMElement)2 AxisFault (org.apache.axis2.AxisFault)2 Pair (org.apache.commons.lang3.tuple.Pair)2