Search in sources :

Example 66 with OAuthApplicationInfo

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

the class ApiMgtDAO method updateApplicationKeyTypeMapping.

/**
 * Update the consumer key and application status for the given key type and application.
 *
 * @param application
 * @param keyType
 * @param keyManagerId
 */
public void updateApplicationKeyTypeMapping(Application application, String keyType, String keyManagerId) throws APIManagementException {
    OAuthApplicationInfo app = application.getOAuthApp(keyType, keyManagerId);
    String consumerKey = null;
    if (app != null) {
        consumerKey = app.getClientId();
    }
    if (consumerKey != null && application.getId() != -1) {
        String addApplicationKeyMapping = SQLConstants.UPDATE_APPLICAITON_KEY_TYPE_MAPPINGS_SQL;
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = APIMgtDBUtil.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(addApplicationKeyMapping);
            ps.setString(1, consumerKey);
            OAuthApplicationInfo oAuthApp = application.getOAuthApp(keyType, keyManagerId);
            String content = new Gson().toJson(oAuthApp);
            ps.setBinaryStream(2, new ByteArrayInputStream(content.getBytes()));
            ps.setInt(3, application.getId());
            ps.setString(4, keyType);
            ps.setString(5, keyManagerId);
            ps.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            handleException("Error updating the CONSUMER KEY of the AM_APPLICATION_KEY_MAPPING table where " + "APPLICATION_ID = " + application.getId() + " and KEY_TYPE = " + keyType, e);
        } finally {
            APIMgtDBUtil.closeAllConnections(ps, connection, null);
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) SQLException(java.sql.SQLException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Connection(java.sql.Connection) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement)

Example 67 with OAuthApplicationInfo

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

the class ApiMgtDAO method getApplicationById.

public Application getApplicationById(int applicationId) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    Application application = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        String query = SQLConstants.GET_APPLICATION_BY_ID_SQL;
        prepStmt = connection.prepareStatement(query);
        prepStmt.setInt(1, applicationId);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            String applicationName = rs.getString("NAME");
            String subscriberId = rs.getString("SUBSCRIBER_ID");
            String subscriberName = rs.getString("USER_ID");
            Subscriber subscriber = new Subscriber(subscriberName);
            subscriber.setId(Integer.parseInt(subscriberId));
            application = new Application(applicationName, subscriber);
            application.setOwner(rs.getString("CREATED_BY"));
            application.setDescription(rs.getString("DESCRIPTION"));
            application.setStatus(rs.getString("APPLICATION_STATUS"));
            application.setCallbackUrl(rs.getString("CALLBACK_URL"));
            application.setId(rs.getInt("APPLICATION_ID"));
            application.setGroupId(rs.getString("GROUP_ID"));
            application.setUUID(rs.getString("UUID"));
            application.setTier(rs.getString("APPLICATION_TIER"));
            application.setTokenType(rs.getString("TOKEN_TYPE"));
            subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
            String tenantDomain = MultitenantUtils.getTenantDomain(subscriberName);
            Map<String, Map<String, OAuthApplicationInfo>> keyMap = getOAuthApplications(tenantDomain, application.getId());
            application.getKeyManagerWiseOAuthApp().putAll(keyMap);
            if (multiGroupAppSharingEnabled) {
                if (application.getGroupId() == null || application.getGroupId().isEmpty()) {
                    application.setGroupId(getGroupId(connection, applicationId));
                }
            }
        }
        if (application != null) {
            Map<String, String> applicationAttributes = getApplicationAttributes(connection, applicationId);
            application.setApplicationAttributes(applicationAttributes);
        }
    } catch (SQLException e) {
        handleException("Error while obtaining details of the Application : " + applicationId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
    return application;
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Application(org.wso2.carbon.apimgt.api.model.Application) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap)

Example 68 with OAuthApplicationInfo

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

the class RegistrationServiceImpl method createOAuthApp.

/**
 * Method to create a OAuth App with client credentials
 *
 * @param appName    application name
 * @param grantTypes grant types
 * @param userName   username of the application
 * @return created Oauth App
 */
private OAuthConsumerAppDTO createOAuthApp(String appName, OAuthApplicationInfo applicationInfo, String grantTypes, String userName) {
    OAuthConsumerAppDTO createdApp = null;
    OAuthAdminService oauthAdminService = new OAuthAdminService();
    OAuthConsumerAppDTO oauthConsumerAppDTO = new OAuthConsumerAppDTO();
    oauthConsumerAppDTO.setApplicationName(appName);
    if (StringUtils.isNotBlank(applicationInfo.getCallBackURL())) {
        oauthConsumerAppDTO.setCallbackUrl(applicationInfo.getCallBackURL());
    }
    oauthConsumerAppDTO.setUsername(userName);
    oauthConsumerAppDTO.setOAuthVersion(OAuthConstants.OAuthVersions.VERSION_2);
    oauthConsumerAppDTO.setGrantTypes(grantTypes.trim());
    try {
        boolean isHashDisabled = OAuth2Util.isHashDisabled();
        if (isHashDisabled) {
            // Creating the Oauth app
            oauthAdminService.registerOAuthApplicationData(oauthConsumerAppDTO);
            // Retrieving the created OAuth application
            createdApp = oauthAdminService.getOAuthApplicationDataByAppName(oauthConsumerAppDTO.getApplicationName());
        } else {
            createdApp = oauthAdminService.registerAndRetrieveOAuthApplicationData(oauthConsumerAppDTO);
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error occurred while creating the OAuth app", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Created OAuth App " + appName);
    }
    return createdApp;
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) OAuthAdminService(org.wso2.carbon.identity.oauth.OAuthAdminService) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)

Example 69 with OAuthApplicationInfo

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

the class AbstractAPIManager method getApplicationKeys.

/**
 * Returns the key associated with given application id.
 *
 * @param applicationId Id of the Application.
 * @return APIKey The key of the application.
 * @throws APIManagementException
 */
protected Set<APIKey> getApplicationKeys(int applicationId, String xWso2Tenant) throws APIManagementException {
    Set<APIKey> apiKeyList = apiMgtDAO.getKeyMappingsFromApplicationId(applicationId);
    if (StringUtils.isNotEmpty(xWso2Tenant)) {
        int tenantId = APIUtil.getInternalOrganizationId(xWso2Tenant);
        // To handle choreo scenario. due to keymanagers are not per organization atm. using ST
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            xWso2Tenant = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
    }
    Set<APIKey> resultantApiKeyList = new HashSet<>();
    for (APIKey apiKey : apiKeyList) {
        String keyManagerName = apiKey.getKeyManager();
        String consumerKey = apiKey.getConsumerKey();
        String tenantDomain = this.tenantDomain;
        if (StringUtils.isNotEmpty(xWso2Tenant)) {
            tenantDomain = xWso2Tenant;
        }
        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.");
                continue;
            }
        }
        if (tenantDomain != null && !tenantDomain.equalsIgnoreCase(keyManagerConfigurationDTO.getOrganization())) {
            continue;
        }
        KeyManager keyManager = null;
        if (keyManagerConfigurationDTO.isEnabled()) {
            keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        } else {
            continue;
        }
        apiKey.setKeyManager(keyManagerConfigurationDTO.getName());
        if (StringUtils.isNotEmpty(consumerKey)) {
            if (keyManager != null) {
                if (APIConstants.OAuthAppMode.MAPPED.name().equalsIgnoreCase(apiKey.getCreateMode()) && !isOauthAppValidation()) {
                    resultantApiKeyList.add(apiKey);
                } else {
                    OAuthApplicationInfo oAuthApplicationInfo = null;
                    try {
                        oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
                    } catch (APIManagementException e) {
                        log.error("Error while retrieving Application Information", e);
                        continue;
                    }
                    if (StringUtils.isNotEmpty(apiKey.getAppMetaData())) {
                        OAuthApplicationInfo storedOAuthApplicationInfo = new Gson().fromJson(apiKey.getAppMetaData(), OAuthApplicationInfo.class);
                        if (oAuthApplicationInfo == null) {
                            oAuthApplicationInfo = storedOAuthApplicationInfo;
                        } else {
                            if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL())) {
                                oAuthApplicationInfo.setCallBackURL(storedOAuthApplicationInfo.getCallBackURL());
                            }
                            if ("null".equalsIgnoreCase(oAuthApplicationInfo.getCallBackURL())) {
                                oAuthApplicationInfo.setCallBackURL("");
                            }
                            if (oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) == null && storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) != null) {
                                if (storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) instanceof String) {
                                    oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, ((String) storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES)).replace(",", " "));
                                } else {
                                    oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
                                }
                            }
                            if (StringUtils.isEmpty(oAuthApplicationInfo.getClientSecret()) && StringUtils.isNotEmpty(storedOAuthApplicationInfo.getClientSecret())) {
                                oAuthApplicationInfo.setClientSecret(storedOAuthApplicationInfo.getClientSecret());
                            }
                        }
                    }
                    AccessTokenInfo tokenInfo = keyManager.getAccessTokenByConsumerKey(consumerKey);
                    if (oAuthApplicationInfo != null) {
                        apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
                        apiKey.setCallbackUrl(oAuthApplicationInfo.getCallBackURL());
                        apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
                        if (oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES) != null) {
                            apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
                        }
                    }
                    if (tokenInfo != null) {
                        apiKey.setAccessToken(tokenInfo.getAccessToken());
                        apiKey.setValidityPeriod(tokenInfo.getValidityPeriod());
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Access token does not exist for Consumer Key: " + consumerKey);
                        }
                    }
                    resultantApiKeyList.add(apiKey);
                }
            } else {
                log.error("Key Manager " + keyManagerName + " not initialized in tenant " + tenantDomain);
            }
        } else {
            resultantApiKeyList.add(apiKey);
        }
    }
    return resultantApiKeyList;
}
Also used : APIKey(org.wso2.carbon.apimgt.api.model.APIKey) KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Gson(com.google.gson.Gson) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 70 with OAuthApplicationInfo

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

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)37 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)30 Test (org.junit.Test)22 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)21 HashMap (java.util.HashMap)19 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)15 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 ArrayList (java.util.ArrayList)13 Map (java.util.Map)13 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)11 Application (org.wso2.carbon.apimgt.api.model.Application)11 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)10 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)10 JsonObject (com.google.gson.JsonObject)9 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)9 ApplicationKeysDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO)9 JSONObject (org.json.simple.JSONObject)8 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)8 Gson (com.google.gson.Gson)7