Search in sources :

Example 11 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO in project carbon-apimgt by wso2.

the class APIConsumerImplTest method testRenewConsumerSecret.

@Test
public void testRenewConsumerSecret() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    String clientId = UUID.randomUUID().toString();
    apiConsumer.apiMgtDAO = apiMgtDAO;
    KeyManagerConfigurationDTO keyManagerConfiguration = new KeyManagerConfigurationDTO();
    keyManagerConfiguration.setEnabled(true);
    Mockito.when(apiMgtDAO.getKeyManagerConfigurationByName(Mockito.anyString(), Mockito.anyString())).thenReturn(keyManagerConfiguration);
    Mockito.when(keyManager.getNewApplicationConsumerSecret(Mockito.anyObject())).thenReturn("updatedClientSecret");
    assertNotNull(apiConsumer.renewConsumerSecret(clientId, APIConstants.KeyManager.DEFAULT_KEY_MANAGER));
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 12 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO in project carbon-apimgt by wso2.

the class APIUtil method getAndSetDefaultKeyManagerConfiguration.

public static KeyManagerConfigurationDTO getAndSetDefaultKeyManagerConfiguration(KeyManagerConfigurationDTO keyManagerConfigurationDTO) throws APIManagementException {
    boolean clientSecretHashEnabled = ServiceReferenceHolder.getInstance().getOauthServerConfiguration().isClientSecretHashEnabled();
    Set<String> availableGrantTypes = ServiceReferenceHolder.getInstance().getOauthServerConfiguration().getSupportedGrantTypes().keySet();
    long validityPeriod = ServiceReferenceHolder.getInstance().getOauthServerConfiguration().getApplicationAccessTokenValidityPeriodInSeconds();
    APIManagerConfigurationService config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService();
    String issuerIdentifier = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenIssuerIdentifier();
    if (config != null) {
        OpenIdConnectConfiguration openIdConnectConfigurations = null;
        APIManagerConfiguration apiManagerConfiguration = config.getAPIManagerConfiguration();
        String keyManagerUrl;
        String enableTokenEncryption = apiManagerConfiguration.getFirstProperty(APIConstants.ENCRYPT_TOKENS_ON_PERSISTENCE);
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.AUTHSERVER_URL)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.AUTHSERVER_URL, apiManagerConfiguration.getFirstProperty(APIConstants.KEYMANAGER_SERVERURL));
        }
        keyManagerUrl = (String) keyManagerConfigurationDTO.getAdditionalProperties().get(APIConstants.AUTHSERVER_URL);
        if (StringUtils.isNotEmpty(keyManagerUrl)) {
            openIdConnectConfigurations = APIUtil.getOpenIdConnectConfigurations(keyManagerUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext(keyManagerConfigurationDTO.getOrganization())).concat(APIConstants.KeyManager.DEFAULT_KEY_MANAGER_OPENID_CONNECT_DISCOVERY_ENDPOINT));
        }
        if (keyManagerConfigurationDTO.getProperty(APIConstants.KeyManager.ENABLE_TOKEN_ENCRYPTION) == null) {
            keyManagerConfigurationDTO.addProperty(APIConstants.ENCRYPT_TOKENS_ON_PERSISTENCE, Boolean.parseBoolean(enableTokenEncryption));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.REVOKE_URL)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.REVOKE_URL, keyManagerUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(APIConstants.IDENTITY_REVOKE_ENDPOINT));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.TOKEN_URL)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.TOKEN_URL, keyManagerUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(APIConstants.IDENTITY_TOKEN_ENDPOINT_CONTEXT));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.AVAILABLE_GRANT_TYPE)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.AVAILABLE_GRANT_TYPE, new ArrayList<>(availableGrantTypes));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.ENABLE_TOKEN_HASH)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.ENABLE_TOKEN_HASH, clientSecretHashEnabled);
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION, true);
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.ENABLE_MAP_OAUTH_CONSUMER_APPS)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.ENABLE_MAP_OAUTH_CONSUMER_APPS, isMapExistingAuthAppsEnabled());
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION, true);
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.TOKEN_ENDPOINT)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.TOKEN_ENDPOINT, keyManagerConfigurationDTO.getAdditionalProperties().get(APIConstants.TOKEN_URL));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.REVOKE_ENDPOINT)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.REVOKE_ENDPOINT, keyManagerConfigurationDTO.getAdditionalProperties().get(APIConstants.REVOKE_URL));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.IDENTITY_OAUTH2_FIELD_VALIDITY_PERIOD)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.IDENTITY_OAUTH2_FIELD_VALIDITY_PERIOD, String.valueOf(validityPeriod));
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.ENABLE_TOKEN_VALIDATION)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.ENABLE_TOKEN_VALIDATION, true);
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.SELF_VALIDATE_JWT)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.SELF_VALIDATE_JWT, true);
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.ISSUER)) {
            if (openIdConnectConfigurations == null) {
                throw new APIMgtInternalException("Error in fetching Open ID configuration.");
            }
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.ISSUER, openIdConnectConfigurations.getIssuer());
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.CLAIM_MAPPING)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.CLAIM_MAPPING, getDefaultClaimMappings());
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.CERTIFICATE_TYPE)) {
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_TYPE, APIConstants.KeyManager.CERTIFICATE_TYPE_JWKS_ENDPOINT);
        }
        if (!keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.CERTIFICATE_VALUE)) {
            if (openIdConnectConfigurations != null) {
                keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_VALUE, openIdConnectConfigurations.getJwksEndpoint());
            } else {
                keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.CERTIFICATE_VALUE, keyManagerUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext(keyManagerConfigurationDTO.getOrganization())).concat(APIConstants.KeyManager.DEFAULT_JWKS_ENDPOINT));
            }
        }
        String defaultKeyManagerType = apiManagerConfiguration.getFirstProperty(APIConstants.DEFAULT_KEY_MANAGER_TYPE);
        if (StringUtils.isNotEmpty(defaultKeyManagerType)) {
            keyManagerConfigurationDTO.setType(defaultKeyManagerType);
        }
    }
    return keyManagerConfigurationDTO;
}
Also used : APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) OpenIdConnectConfiguration(org.wso2.carbon.apimgt.impl.kmclient.model.OpenIdConnectConfiguration) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService)

Example 13 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO in project carbon-apimgt by wso2.

the class KeyMgtNotificationSender method notify.

public void notify(KeyManagerConfigurationDTO keyManagerConfigurationDTO, String action) {
    String encodedString = "";
    if (keyManagerConfigurationDTO.getAdditionalProperties() != null) {
        String additionalProperties = new Gson().toJson(keyManagerConfigurationDTO.getAdditionalProperties());
        encodedString = new String(Base64.encodeBase64(additionalProperties.getBytes()));
    }
    Object[] objects = new Object[] { APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_CONFIGURATION, action, keyManagerConfigurationDTO.getName(), keyManagerConfigurationDTO.getType(), keyManagerConfigurationDTO.isEnabled(), encodedString, keyManagerConfigurationDTO.getOrganization(), keyManagerConfigurationDTO.getTokenType() };
    Event keyManagerEvent = new Event(APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_STREAM_ID, System.currentTimeMillis(), null, null, objects);
    EventHubConfigurationDto eventHubConfigurationDto = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getEventHubConfigurationDto();
    if (eventHubConfigurationDto.isEnabled()) {
        EventPublisherEvent notificationEvent = new EventPublisherEvent(APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_STREAM_ID, System.currentTimeMillis(), objects, keyManagerEvent.toString());
        APIUtil.publishEvent(EventPublisherType.KEYMGT_EVENT, notificationEvent, keyManagerEvent.toString());
    }
}
Also used : EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) EventPublisherEvent(org.wso2.carbon.apimgt.eventing.EventPublisherEvent) Gson(com.google.gson.Gson) Event(org.wso2.carbon.databridge.commons.Event) EventPublisherEvent(org.wso2.carbon.apimgt.eventing.EventPublisherEvent)

Example 14 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO in project carbon-apimgt by wso2.

the class OrganizationPurgeDAO method deleteKeyManagerConfigurationList.

public void deleteKeyManagerConfigurationList(List<KeyManagerConfigurationDTO> kmList, String organization) throws APIManagementException {
    List<String> kmIdList = kmList.stream().map(KeyManagerConfigurationDTO::getUuid).collect(Collectors.toList());
    List<String> collectionList = Collections.nCopies(kmIdList.size(), "?");
    try (Connection conn = APIMgtDBUtil.getConnection()) {
        conn.setAutoCommit(false);
        String deleteKMQuery = OrganizationPurgeConstants.DELETE_BULK_KEY_MANAGER_LIST_SQL.replaceAll(OrganizationPurgeConstants.KM_UUID_REGEX, String.join(",", collectionList));
        try (PreparedStatement preparedStatement = conn.prepareStatement(deleteKMQuery)) {
            preparedStatement.setString(1, organization);
            int index = 1;
            for (String uuid : kmIdList) {
                preparedStatement.setString(index + 1, uuid);
                index++;
            }
            preparedStatement.execute();
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while deleting key managers:  " + kmIdList + " in organization " + organization, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 15 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO 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)

Aggregations

KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)43 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)30 Gson (com.google.gson.Gson)16 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)12 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)11 JSONObject (org.json.simple.JSONObject)10 JsonObject (com.google.gson.JsonObject)9 PreparedStatement (java.sql.PreparedStatement)9 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)9 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)9 Map (java.util.Map)8 APIAdmin (org.wso2.carbon.apimgt.api.APIAdmin)8 APIAdminImpl (org.wso2.carbon.apimgt.impl.APIAdminImpl)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 Connection (java.sql.Connection)7 SQLException (java.sql.SQLException)7 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)7 LinkedHashMap (java.util.LinkedHashMap)6 Application (org.wso2.carbon.apimgt.api.model.Application)6