Search in sources :

Example 31 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class JWTGenerator method populateCustomClaims.

@Override
public Map<String, String> populateCustomClaims(TokenValidationContext validationContext) throws APIManagementException {
    APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    JWTConfigurationDto jwtConfigurationDto = apiManagerConfiguration.getJwtConfigurationDto();
    Map<String, String> customClaims = new HashMap<>();
    Map<String, Object> properties = new HashMap<>();
    String username = validationContext.getValidationInfoDTO().getEndUserName();
    int tenantId = APIUtil.getTenantId(username);
    if (jwtConfigurationDto.isEnableUserClaims()) {
        String accessToken = validationContext.getAccessToken();
        if (accessToken != null) {
            properties.put(APIConstants.KeyManager.ACCESS_TOKEN, accessToken);
        }
        String dialectURI = jwtConfigurationDto.getConsumerDialectUri();
        if (!StringUtils.isEmpty(dialectURI)) {
            properties.put(APIConstants.KeyManager.CLAIM_DIALECT, dialectURI);
            String keymanagerName = validationContext.getValidationInfoDTO().getKeyManager();
            KeyManager keymanager = KeyManagerHolder.getKeyManagerInstance(APIUtil.getTenantDomainFromTenantId(tenantId), keymanagerName);
            if (keymanager != null) {
                customClaims = keymanager.getUserClaims(username, properties);
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved claims :" + customClaims);
                }
            }
        }
    }
    ClaimsRetriever claimsRetriever = getClaimsRetriever();
    if (claimsRetriever != null) {
        customClaims.putAll(claimsRetriever.getClaims(username));
    }
    return customClaims;
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) ClaimsRetriever(org.wso2.carbon.apimgt.impl.token.ClaimsRetriever) JWTConfigurationDto(org.wso2.carbon.apimgt.common.gateway.dto.JWTConfigurationDto)

Example 32 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIConsumerImpl method updateAuthClient.

/**
 * @param userId Subscriber name.
 * @param application The Application.
 * @param tokenType Token type (PRODUCTION | SANDBOX)
 * @param callbackUrl callback URL
 * @param allowedDomains allowedDomains for token.
 * @param validityTime validity time period.
 * @param tokenScope Scopes for the requested tokens.
 * @param groupingId APIM application id.
 * @param jsonString Callback URL for the Application.
 * @param keyManagerID Key Manager ID of the relevant Key Manager
 * @return
 * @throws APIManagementException
 */
@Override
public OAuthApplicationInfo updateAuthClient(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String groupingId, String jsonString, String keyManagerID) throws APIManagementException {
    boolean tenantFlowStarted = false;
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            tenantFlowStarted = true;
        }
        final String subscriberName = application.getSubscriber().getName();
        boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
        boolean isUserAppOwner;
        if (isCaseInsensitiveComparisons) {
            isUserAppOwner = subscriberName.equalsIgnoreCase(userId);
        } else {
            isUserAppOwner = subscriberName.equals(userId);
        }
        if (!isUserAppOwner) {
            throw new APIManagementException("user: " + userId + ", attempted to update OAuth application " + "owned by: " + subscriberName);
        }
        String keyManagerName;
        KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerID);
        String keyManagerTenant;
        if (keyManagerConfiguration != null) {
            keyManagerName = keyManagerConfiguration.getName();
            keyManagerTenant = keyManagerConfiguration.getOrganization();
        } else {
            // keeping this just in case the name is sent by mistake.
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerID);
            if (keyManagerConfiguration == null) {
                throw new APIManagementException("Key Manager " + keyManagerID + " couldn't found.", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
            } else {
                keyManagerName = keyManagerID;
                keyManagerID = keyManagerConfiguration.getUuid();
                keyManagerTenant = keyManagerConfiguration.getOrganization();
            }
        }
        if (!keyManagerConfiguration.isEnabled()) {
            throw new APIManagementException("Key Manager " + keyManagerName + " not activated in the requested " + "Tenant", ExceptionCodes.KEY_MANAGER_NOT_ENABLED);
        }
        if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORTED_TOKEN_GENERATION);
        }
        // Create OauthAppRequest object by passing json String.
        OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, application.getTokenType(), keyManagerTenant, keyManagerName);
        oauthAppRequest.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
        String consumerKey = apiMgtDAO.getConsumerKeyByApplicationIdKeyTypeKeyManager(application.getId(), tokenType, keyManagerID);
        oauthAppRequest.getOAuthApplicationInfo().setClientId(consumerKey);
        // get key manager instance.
        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerTenant, keyManagerName);
        if (keyManager == null) {
            throw new APIManagementException("Key Manager " + keyManagerName + " not initialized in the requested" + "Tenant", ExceptionCodes.KEY_MANAGER_INITIALIZATION_FAILED);
        }
        // set application attributes
        oauthAppRequest.getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
        oauthAppRequest.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
        // call update method.
        OAuthApplicationInfo updatedAppInfo = keyManager.updateApplication(oauthAppRequest);
        apiMgtDAO.updateApplicationKeyTypeMetaData(application.getId(), tokenType, keyManagerID, updatedAppInfo);
        JSONObject appLogObject = new JSONObject();
        appLogObject.put(APIConstants.AuditLogConstants.APPLICATION_NAME, updatedAppInfo.getClientName());
        appLogObject.put("Updated Oauth app with Call back URL", callbackUrl);
        appLogObject.put("Updated Oauth app with grant types", jsonString);
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
        return updatedAppInfo;
    } finally {
        if (tenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 33 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validateSubscription.

@Override
public APIKeyValidationInfoDTO validateSubscription(String apiContext, String apiVersion, String consumerKey, String keyManager) {
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    try {
        if (log.isDebugEnabled()) {
            log.debug("Before validating subscriptions");
            log.debug("Validation Info : { context : " + apiContext + " , " + "version : " + apiVersion + " , consumerKey : " + consumerKey + " }");
        }
        validateSubscriptionDetails(apiContext, apiVersion, consumerKey, keyManager, apiKeyValidationInfoDTO);
        if (log.isDebugEnabled()) {
            log.debug("After validating subscriptions");
        }
    } catch (APIManagementException e) {
        log.error("Error Occurred while validating subscription.", e);
    }
    return apiKeyValidationInfoDTO;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 34 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validate.

private APIKeyValidationInfoDTO validate(APIKeyValidationInfoDTO infoDTO, String apiTenantDomain, int tenantId, SubscriptionDataStore datastore, API api, ApplicationKeyMapping key, Application app, Subscription sub, String keyManager) {
    String subscriptionStatus = sub.getSubscriptionState();
    String type = key.getKeyType();
    if (APIConstants.SubscriptionStatus.BLOCKED.equals(subscriptionStatus)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
        infoDTO.setAuthorized(false);
        return infoDTO;
    } else if (APIConstants.SubscriptionStatus.ON_HOLD.equals(subscriptionStatus) || APIConstants.SubscriptionStatus.REJECTED.equals(subscriptionStatus)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.SUBSCRIPTION_INACTIVE);
        infoDTO.setAuthorized(false);
        return infoDTO;
    } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subscriptionStatus) && !APIConstants.API_KEY_TYPE_SANDBOX.equals(type)) {
        infoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_BLOCKED);
        infoDTO.setType(type);
        infoDTO.setAuthorized(false);
        return infoDTO;
    }
    infoDTO.setTier(sub.getPolicyId());
    infoDTO.setSubscriber(app.getSubName());
    infoDTO.setApplicationId(app.getId().toString());
    infoDTO.setApiName(api.getApiName());
    infoDTO.setApiVersion(api.getApiVersion());
    infoDTO.setApiPublisher(api.getApiProvider());
    infoDTO.setApplicationName(app.getName());
    infoDTO.setApplicationTier(app.getPolicy());
    infoDTO.setApplicationUUID(app.getUUID());
    infoDTO.setAppAttributes(app.getAttributes());
    infoDTO.setType(type);
    // Advanced Level Throttling Related Properties
    String apiTier = api.getApiTier();
    String subscriberTenant = MultitenantUtils.getTenantDomain(app.getSubName());
    ApplicationPolicy appPolicy = datastore.getApplicationPolicyByName(app.getPolicy(), APIUtil.getTenantIdFromTenantDomain(app.getOrganization()));
    if (appPolicy == null) {
        try {
            appPolicy = new SubscriptionDataLoaderImpl().getApplicationPolicy(app.getPolicy(), app.getOrganization());
            datastore.addOrUpdateApplicationPolicy(appPolicy);
        } catch (DataLoadingException e) {
            log.error("Error while loading ApplicationPolicy");
        }
    }
    SubscriptionPolicy subPolicy = datastore.getSubscriptionPolicyByName(sub.getPolicyId(), tenantId);
    if (subPolicy == null) {
        try {
            subPolicy = new SubscriptionDataLoaderImpl().getSubscriptionPolicy(sub.getPolicyId(), apiTenantDomain);
            datastore.addOrUpdateSubscriptionPolicy(subPolicy);
        } catch (DataLoadingException e) {
            log.error("Error while loading SubscriptionPolicy");
        }
    }
    ApiPolicy apiPolicy = datastore.getApiPolicyByName(api.getApiTier(), tenantId);
    boolean isContentAware = false;
    if (appPolicy.isContentAware() || subPolicy.isContentAware() || (apiPolicy != null && apiPolicy.isContentAware())) {
        isContentAware = true;
    }
    infoDTO.setContentAware(isContentAware);
    // TODO this must implement as a part of throttling implementation.
    int spikeArrest = 0;
    String apiLevelThrottlingKey = "api_level_throttling_key";
    if (subPolicy.getRateLimitCount() > 0) {
        spikeArrest = subPolicy.getRateLimitCount();
    }
    String spikeArrestUnit = null;
    if (subPolicy.getRateLimitTimeUnit() != null) {
        spikeArrestUnit = subPolicy.getRateLimitTimeUnit();
    }
    boolean stopOnQuotaReach = subPolicy.isStopOnQuotaReach();
    int graphQLMaxDepth = 0;
    if (subPolicy.getGraphQLMaxDepth() > 0) {
        graphQLMaxDepth = subPolicy.getGraphQLMaxDepth();
    }
    int graphQLMaxComplexity = 0;
    if (subPolicy.getGraphQLMaxComplexity() > 0) {
        graphQLMaxComplexity = subPolicy.getGraphQLMaxComplexity();
    }
    List<String> list = new ArrayList<String>();
    list.add(apiLevelThrottlingKey);
    infoDTO.setSpikeArrestLimit(spikeArrest);
    infoDTO.setSpikeArrestUnit(spikeArrestUnit);
    infoDTO.setStopOnQuotaReach(stopOnQuotaReach);
    infoDTO.setSubscriberTenantDomain(subscriberTenant);
    infoDTO.setGraphQLMaxDepth(graphQLMaxDepth);
    infoDTO.setGraphQLMaxComplexity(graphQLMaxComplexity);
    if (apiTier != null && apiTier.trim().length() > 0) {
        infoDTO.setApiTier(apiTier);
    }
    // We also need to set throttling data list associated with given API. This need to have
    // policy id and
    // condition id list for all throttling tiers associated with this API.
    infoDTO.setThrottlingDataList(list);
    infoDTO.setAuthorized(true);
    return infoDTO;
}
Also used : SubscriptionDataLoaderImpl(org.wso2.carbon.apimgt.keymgt.model.impl.SubscriptionDataLoaderImpl) DataLoadingException(org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException) SubscriptionPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationPolicy) ApiPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy) ArrayList(java.util.ArrayList)

Example 35 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class DefaultKeyValidationHandler method getAccessTokenInfo.

private AccessTokenInfo getAccessTokenInfo(TokenValidationContext validationContext) throws APIManagementException {
    Object cachedAccessTokenInfo = CacheProvider.createIntrospectionCache().get(validationContext.getAccessToken());
    if (cachedAccessTokenInfo != null) {
        log.debug("AccessToken available in introspection Cache.");
        return (AccessTokenInfo) cachedAccessTokenInfo;
    }
    String electedKeyManager = null;
    // Obtaining details about the token.
    if (StringUtils.isNotEmpty(validationContext.getTenantDomain())) {
        Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(validationContext.getTenantDomain());
        KeyManager keyManagerInstance = null;
        if (tenantKeyManagers.values().size() == 1) {
            log.debug("KeyManager count is 1");
            Map.Entry<String, KeyManagerDto> entry = tenantKeyManagers.entrySet().iterator().next();
            if (entry != null) {
                KeyManagerDto keyManagerDto = entry.getValue();
                if (keyManagerDto != null && (validationContext.getKeyManagers().contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || validationContext.getKeyManagers().contains(keyManagerDto.getName()))) {
                    if (log.isDebugEnabled()) {
                        log.debug("KeyManager " + keyManagerDto.getName() + " Available in API level KM list " + String.join(",", validationContext.getKeyManagers()));
                    }
                    if (keyManagerDto.getKeyManager() != null && keyManagerDto.getKeyManager().canHandleToken(validationContext.getAccessToken())) {
                        if (log.isDebugEnabled()) {
                            log.debug("KeyManager " + keyManagerDto.getName() + " can handle the token");
                        }
                        keyManagerInstance = keyManagerDto.getKeyManager();
                        electedKeyManager = entry.getKey();
                    }
                }
            }
        } else if (tenantKeyManagers.values().size() > 1) {
            log.debug("KeyManager count is > 1");
            if (validationContext.getKeyManagers().contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS)) {
                if (log.isDebugEnabled()) {
                    log.debug("API level KeyManagers contains " + APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS);
                }
                for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
                    if (keyManagerDtoEntry.getValue().getKeyManager() != null && keyManagerDtoEntry.getValue().getKeyManager().canHandleToken(validationContext.getAccessToken())) {
                        if (log.isDebugEnabled()) {
                            log.debug("KeyManager " + keyManagerDtoEntry.getValue().getName() + " can handle the token");
                        }
                        keyManagerInstance = keyManagerDtoEntry.getValue().getKeyManager();
                        electedKeyManager = keyManagerDtoEntry.getKey();
                        break;
                    }
                }
            } else {
                for (String selectedKeyManager : validationContext.getKeyManagers()) {
                    KeyManagerDto keyManagerDto = tenantKeyManagers.get(selectedKeyManager);
                    if (keyManagerDto != null && keyManagerDto.getKeyManager() != null && keyManagerDto.getKeyManager().canHandleToken(validationContext.getAccessToken())) {
                        if (log.isDebugEnabled()) {
                            log.debug("KeyManager " + keyManagerDto.getName() + " can handle the token");
                        }
                        keyManagerInstance = keyManagerDto.getKeyManager();
                        electedKeyManager = selectedKeyManager;
                        break;
                    }
                }
            }
        }
        if (keyManagerInstance != null) {
            log.debug("KeyManager instance available to validate token.");
            AccessTokenInfo tokenInfo = keyManagerInstance.getTokenMetaData(validationContext.getAccessToken());
            tokenInfo.setKeyManager(electedKeyManager);
            CacheProvider.getGatewayIntrospectCache().put(validationContext.getAccessToken(), tokenInfo);
            return tokenInfo;
        } else {
            AccessTokenInfo tokenInfo = new AccessTokenInfo();
            tokenInfo.setTokenValid(false);
            tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
            log.debug("KeyManager not available to authorize token.");
            return tokenInfo;
        }
    }
    return null;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) Map(java.util.Map)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)38 Test (org.junit.Test)29 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 HashMap (java.util.HashMap)21 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 FileInputStream (java.io.FileInputStream)16 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)16 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)16 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)16 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)16 Map (java.util.Map)14 API (org.wso2.carbon.apimgt.core.models.API)14 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)13 Scope (org.wso2.carbon.apimgt.core.models.Scope)13 KeyManagerDto (org.wso2.carbon.apimgt.impl.dto.KeyManagerDto)13 TreeMap (java.util.TreeMap)11 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)11