Search in sources :

Example 91 with KeyManager

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

the class AbstractApplicationRegistrationWorkflowExecutor method dogenerateKeysForApplication.

public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO) throws APIManagementException {
    log.debug("Registering Application and creating an Access Token... ");
    Application application = workflowDTO.getApplication();
    Subscriber subscriber = application.getSubscriber();
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
        dao.populateAppRegistrationWorkflowDTO(workflowDTO);
    }
    try {
        // get new key manager
        // Here the default flow is set expecting an ID as the keymanager as this flow only involves new applications
        String keyManagerId = workflowDTO.getKeyManager();
        KeyManagerConfigurationDTO km = dao.getKeyManagerConfigurationByUUID(keyManagerId);
        String tenantDomain = km.getOrganization();
        String keyManagerName = km.getName();
        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        if (keyManager == null) {
            throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
        }
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().setClientName(application.getName());
        // set applications attributes to the oAuthApplicationInfo
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
        // createApplication on oAuthorization server.
        OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());
        // update associateApplication
        ApplicationUtils.updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerId);
        // change create application status in to completed.
        dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED, workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerId);
        workflowDTO.setApplicationInfo(oAuthApplication);
        AccessTokenInfo tokenInfo;
        Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
        if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
            AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
            tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
        } else {
            tokenInfo = new AccessTokenInfo();
            tokenInfo.setAccessToken("");
            tokenInfo.setValidityPeriod(0L);
            String[] noScopes = new String[] { "N/A" };
            tokenInfo.setScope(noScopes);
            oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
        }
        workflowDTO.setAccessTokenInfo(tokenInfo);
    } catch (Exception e) {
        APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) Application(org.wso2.carbon.apimgt.api.model.Application) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 92 with KeyManager

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

the class APIKeyValidationService method validateKey.

/**
 * Validates the access tokens issued for a particular user to access an API.
 *
 * @param context     Requested context
 * @param accessToken Provided access token
 * @return APIKeyValidationInfoDTO with authorization info and tier info if authorized. If it is not
 * authorized, tier information will be <pre>null</pre>
 * @throws APIKeyMgtException Error occurred when accessing the underlying database or registry.
 */
public APIKeyValidationInfoDTO validateKey(String context, String version, String accessToken, String requiredAuthenticationLevel, String matchingResource, String httpVerb, String tenantDomain, List keyManagers) throws APIKeyMgtException, APIManagementException {
    TracingSpan validateMainSpan = null;
    TracingSpan getAccessTokenCacheSpan = null;
    TracingSpan fetchingKeyValDTOSpan = null;
    TracingSpan validateTokenSpan = null;
    TracingSpan validateSubscriptionSpan = null;
    TracingSpan validateScopeSpan = null;
    TracingSpan generateJWTSpan = null;
    TracingSpan keyCache = null;
    TracingSpan keyValResponseSpan = null;
    TracingTracer tracer = Util.getGlobalTracer();
    Timer timer = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "VALIDATE_MAIN"));
    Timer.Context timerContext = timer.start();
    MessageContext axis2MessageContext = MessageContext.getCurrentMessageContext();
    if (Util.tracingEnabled() && axis2MessageContext != null) {
        Map map = (Map) axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);
        TracingSpan spanContext = Util.extract(tracer, map);
        validateMainSpan = Util.startSpan(TracingConstants.VALIDATE_MAIN, spanContext, tracer);
    }
    Map headersMap = null;
    String activityID = null;
    try {
        if (axis2MessageContext != null) {
            MessageContext responseMessageContext = axis2MessageContext.getOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            if (responseMessageContext != null) {
                if (log.isDebugEnabled()) {
                    List headersList = new ArrayList();
                    Object headers = axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
                    if (headers != null && headers instanceof Map) {
                        headersMap = (Map) headers;
                        activityID = (String) headersMap.get("activityID");
                    }
                    if (headersMap != null) {
                        headersList.add(new Header("activityID", (String) headersMap.get("activityID")));
                    }
                    responseMessageContext.setProperty(HTTPConstants.HTTP_HEADERS, headersList);
                }
            }
        }
    } catch (AxisFault axisFault) {
        throw new APIKeyMgtException("Error while building response messageContext: " + axisFault.getLocalizedMessage());
    }
    if (log.isDebugEnabled()) {
        String logMsg = "KeyValidation request from gateway: requestTime= " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()) + " , for:" + context + " with accessToken=" + accessToken;
        if (activityID != null) {
            logMsg = logMsg + " , transactionId=" + activityID;
        }
        log.debug(logMsg);
    }
    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setAccessToken(accessToken);
    validationContext.setContext(context);
    validationContext.setHttpVerb(httpVerb);
    validationContext.setMatchingResource(matchingResource);
    validationContext.setRequiredAuthenticationLevel(requiredAuthenticationLevel);
    validationContext.setValidationInfoDTO(new APIKeyValidationInfoDTO());
    validationContext.setVersion(version);
    validationContext.setTenantDomain(tenantDomain);
    validationContext.setKeyManagers(keyManagers);
    if (Util.tracingEnabled()) {
        getAccessTokenCacheSpan = Util.startSpan(TracingConstants.GET_ACCESS_TOKEN_CACHE_KEY, validateMainSpan, tracer);
    }
    String cacheKey = APIUtil.getAccessTokenCacheKey(accessToken, context, version, matchingResource, httpVerb, requiredAuthenticationLevel);
    validationContext.setCacheKey(cacheKey);
    if (Util.tracingEnabled()) {
        Util.finishSpan(getAccessTokenCacheSpan);
        fetchingKeyValDTOSpan = Util.startSpan(TracingConstants.FETCHING_API_KEY_VAL_INFO_DTO_FROM_CACHE, validateMainSpan, tracer);
    }
    APIKeyValidationInfoDTO infoDTO = APIKeyMgtUtil.getFromKeyManagerCache(cacheKey);
    if (Util.tracingEnabled()) {
        Util.finishSpan(fetchingKeyValDTOSpan);
    }
    if (infoDTO != null) {
        validationContext.setCacheHit(true);
        log.debug("APIKeyValidationInfoDTO fetched from cache. Setting cache hit to true...");
        validationContext.setValidationInfoDTO(infoDTO);
    }
    log.debug("Before calling Validate Token method...");
    Timer timer2 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "VALIDATE_TOKEN"));
    Timer.Context timerContext2 = timer2.start();
    if (Util.tracingEnabled()) {
        validateTokenSpan = Util.startSpan(TracingConstants.VALIDATE_TOKEN, validateMainSpan, tracer);
    }
    KeyValidationHandler keyValidationHandler = ServiceReferenceHolder.getInstance().getKeyValidationHandler(tenantDomain);
    boolean state = keyValidationHandler.validateToken(validationContext);
    timerContext2.stop();
    if (Util.tracingEnabled()) {
        Util.finishSpan(validateTokenSpan);
    }
    log.debug("State after calling validateToken ... " + state);
    if (state) {
        Timer timer3 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "VALIDATE_SUBSCRIPTION"));
        Timer.Context timerContext3 = timer3.start();
        if (Util.tracingEnabled()) {
            validateSubscriptionSpan = Util.startSpan(TracingConstants.VALIDATE_SUBSCRIPTION, validateMainSpan, tracer);
        }
        state = keyValidationHandler.validateSubscription(validationContext);
        timerContext3.stop();
        if (Util.tracingEnabled()) {
            Util.finishSpan(validateSubscriptionSpan);
        }
    }
    log.debug("State after calling validateSubscription... " + state);
    if (state) {
        Timer timer4 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "VALIDATE_SCOPES"));
        Timer.Context timerContext4 = timer4.start();
        if (Util.tracingEnabled()) {
            validateScopeSpan = Util.startSpan(TracingConstants.VALIDATE_SCOPES, validateMainSpan, tracer);
        }
        state = keyValidationHandler.validateScopes(validationContext);
        timerContext4.stop();
        if (Util.tracingEnabled()) {
            Util.finishSpan(validateScopeSpan);
        }
    }
    log.debug("State after calling validateScopes... " + state);
    if (state && APIKeyMgtDataHolder.isJwtGenerationEnabled() && validationContext.getValidationInfoDTO().getEndUserName() != null && !validationContext.isCacheHit()) {
        Timer timer5 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GENERATE_JWT"));
        Timer.Context timerContext5 = timer5.start();
        if (Util.tracingEnabled()) {
            generateJWTSpan = Util.startSpan(TracingConstants.GENERATE_JWT, validateMainSpan, tracer);
        }
        keyValidationHandler.generateConsumerToken(validationContext);
        timerContext5.stop();
        if (Util.tracingEnabled()) {
            Util.finishSpan(generateJWTSpan);
        }
    }
    log.debug("State after calling generateConsumerToken... " + state);
    if (!validationContext.isCacheHit()) {
        if (Util.tracingEnabled()) {
            keyCache = Util.startSpan(TracingConstants.WRITE_TO_KEY_MANAGER_CACHE, validateMainSpan, tracer);
        }
        APIKeyMgtUtil.writeToKeyManagerCache(cacheKey, validationContext.getValidationInfoDTO());
        if (Util.tracingEnabled()) {
            Util.finishSpan(keyCache);
        }
    }
    if (Util.tracingEnabled()) {
        keyValResponseSpan = Util.startSpan(TracingConstants.PUBLISHING_KEY_VALIDATION_RESPONSE, validateMainSpan, tracer);
    }
    if (log.isDebugEnabled() && axis2MessageContext != null) {
        logMessageDetails(axis2MessageContext, validationContext.getValidationInfoDTO());
    }
    if (log.isDebugEnabled()) {
        log.debug("APIKeyValidationInfoDTO before returning : " + validationContext.getValidationInfoDTO());
        log.debug("KeyValidation response from keymanager to gateway for access token:" + accessToken + " at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
    if (Util.tracingEnabled()) {
        Util.finishSpan(keyValResponseSpan);
    }
    timerContext.stop();
    if (Util.tracingEnabled() && validateMainSpan != null) {
        Util.finishSpan(validateMainSpan);
    }
    return validationContext.getValidationInfoDTO();
}
Also used : AxisFault(org.apache.axis2.AxisFault) TracingTracer(org.wso2.carbon.apimgt.tracing.TracingTracer) ArrayList(java.util.ArrayList) Date(java.util.Date) APIKeyMgtException(org.wso2.carbon.apimgt.keymgt.APIKeyMgtException) Timer(org.wso2.carbon.metrics.manager.Timer) Header(org.apache.commons.httpclient.Header) KeyValidationHandler(org.wso2.carbon.apimgt.keymgt.handlers.KeyValidationHandler) ArrayList(java.util.ArrayList) List(java.util.List) TracingSpan(org.wso2.carbon.apimgt.tracing.TracingSpan) MessageContext(org.apache.axis2.context.MessageContext) HashMap(java.util.HashMap) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 93 with KeyManager

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

the class SubscriptionDataStoreImpl method getKeyMappingByKeyAndKeyManager.

@Override
public ApplicationKeyMapping getKeyMappingByKeyAndKeyManager(String key, String keyManager) {
    ApplicationKeyMappingCacheKey applicationKeyMappingCacheKey = new ApplicationKeyMappingCacheKey(key, keyManager);
    String synchronizeKey = "SubscriptionDataStoreImpl-KeyMapping-" + applicationKeyMappingCacheKey;
    ApplicationKeyMapping applicationKeyMapping = applicationKeyMappingMap.get(applicationKeyMappingCacheKey);
    if (applicationKeyMapping == null) {
        synchronized (synchronizeKey.intern()) {
            applicationKeyMapping = applicationKeyMappingMap.get(applicationKeyMappingCacheKey);
            if (applicationKeyMapping != null) {
                return applicationKeyMapping;
            }
            try {
                applicationKeyMapping = new SubscriptionDataLoaderImpl().getKeyMapping(key, keyManager, tenantDomain);
            } catch (DataLoadingException e) {
                log.error("Error while Loading KeyMapping Information from Internal API.", e);
            }
            if (applicationKeyMapping != null && !StringUtils.isEmpty(applicationKeyMapping.getConsumerKey())) {
                // load to the memory
                log.debug("Loading Keymapping to the in-memory datastore.");
                addOrUpdateApplicationKeyMapping(applicationKeyMapping);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Retrieving Application information with Consumer Key : " + key + " and keymanager : " + keyManager);
        if (applicationKeyMapping != null) {
            log.debug("Retrieved Application information with Consumer Key : " + key + " and keymanager : " + keyManager + " is " + applicationKeyMapping.toString());
        } else {
            log.debug("Retrieving Application information with Consumer Key : " + key + " and keymanager : " + keyManager + " is empty");
        }
    }
    return applicationKeyMapping;
}
Also used : DataLoadingException(org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException) ApplicationKeyMappingCacheKey(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMappingCacheKey) ApplicationKeyMapping(org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMapping)

Example 94 with KeyManager

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

the class KeyManagersApiServiceImpl method keyManagersGet.

public Response keyManagersGet(String xWSO2Tenant, MessageContext messageContext) {
    String organization = RestApiUtil.getOrganization(messageContext);
    APIAdmin apiAdmin = new APIAdminImpl();
    try {
        List<KeyManagerConfigurationDTO> keyManagerConfigurations = apiAdmin.getKeyManagerConfigurationsByOrganization(organization);
        return Response.ok(KeyManagerMappingUtil.toKeyManagerListDto(keyManagerConfigurations)).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving keyManager Details for organization " + organization, log);
    }
    return null;
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl)

Example 95 with KeyManager

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

the class APIConsumerImpl method renewConsumerSecret.

/**
 * Regenerate consumer secret.
 *
 * @param clientId For which consumer key we need to regenerate consumer secret.
 * @param keyManagerName
 * @return New consumer secret.
 * @throws APIManagementException This is the custom exception class for API management.
 */
public String renewConsumerSecret(String clientId, String keyManagerName) throws APIManagementException {
    // Create Token Request with parameters provided from UI.
    AccessTokenRequest tokenRequest = new AccessTokenRequest();
    tokenRequest.setClientId(clientId);
    KeyManagerConfigurationDTO keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
    if (keyManagerConfigurationDTO == null) {
        keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
        if (keyManagerConfigurationDTO != null) {
            keyManagerName = keyManagerConfigurationDTO.getName();
        } else {
            log.error("Key Manager: " + keyManagerName + " not found in database.");
            throw new APIManagementException("Key Manager " + keyManagerName + " not found in database.", ExceptionCodes.KEY_MANAGER_NOT_FOUND);
        }
    }
    KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
    return keyManager.getNewApplicationConsumerSecret(tokenRequest);
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

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