Search in sources :

Example 41 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerConfigurationDTO 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 42 with KeyManagerConfigurationDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerConfigurationDTO 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 43 with KeyManagerConfigurationDTO

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

Example 44 with KeyManagerConfigurationDTO

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

the class APIConsumerImpl method mapExistingOAuthClient.

/**
 * @param jsonString this string will contain oAuth app details
 * @param userName user name of logged in user.
 * @param clientId this is the consumer key of oAuthApplication
 * @param applicationName this is the APIM appication name.
 * @param keyType
 * @param tokenType this is theApplication Token Type. This can be either default or jwt.
 * @param keyManagerName key Manager name
 * @return
 * @throws APIManagementException
 */
@Override
public Map<String, Object> mapExistingOAuthClient(String jsonString, String userName, String clientId, String applicationName, String keyType, String tokenType, String keyManagerName, String tenantDomain) throws APIManagementException {
    String callBackURL = null;
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantUtils.getTenantDomain(userName);
    }
    String keyManagerId = null;
    KeyManagerConfigurationDTO keyManagerConfiguration = null;
    if (keyManagerName != null) {
        keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfiguration == null) {
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfiguration != null) {
                keyManagerId = keyManagerName;
                keyManagerName = keyManagerConfiguration.getName();
            }
        } else {
            keyManagerId = keyManagerConfiguration.getUuid();
        }
    } else {
        keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
        keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        keyManagerId = keyManagerConfiguration.getUuid();
    }
    if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
        throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
    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_SUPPORT_OAUTH_APP_CREATION);
    }
    OAuthAppRequest oauthAppRequest = ApplicationUtils.createOauthAppRequest(applicationName, clientId, callBackURL, "default", jsonString, tokenType, tenantDomain, keyManagerName);
    // if clientId is null in the argument `ApplicationUtils#createOauthAppRequest` will set it using
    // the props in `jsonString`. Hence we are taking the updated `clientId` here
    clientId = oauthAppRequest.getOAuthApplicationInfo().getClientId();
    KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
    if (keyManager == null) {
        throw new APIManagementException("Key Manager " + keyManagerName + "Couldn't initialized in tenant " + tenantDomain + ".", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
    // Get application ID
    int applicationId = apiMgtDAO.getApplicationId(applicationName, userName);
    // Checking if clientId is mapped with another application.
    if (apiMgtDAO.isKeyMappingExistsForConsumerKeyOrApplication(applicationId, keyManagerName, keyManagerId, keyType, clientId)) {
        throw new APIManagementException("Key Mappings already exists for application " + applicationName + " or consumer key " + clientId, ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
    }
    if (log.isDebugEnabled()) {
        log.debug("Client ID " + clientId + " not mapped previously with another application. No existing " + "key mappings available for application " + applicationName);
    }
    // createApplication on oAuthorization server.
    OAuthApplicationInfo oAuthApplication = isOauthAppValidation() ? keyManager.mapOAuthApplication(oauthAppRequest) : oauthAppRequest.getOAuthApplicationInfo();
    // Do application mapping with consumerKey.
    String keyMappingId = UUID.randomUUID().toString();
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(keyType, applicationId, clientId, keyManagerId, keyMappingId);
    Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
    AccessTokenInfo tokenInfo;
    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));
    }
    Map<String, Object> keyDetails = new HashMap<String, Object>();
    if (tokenInfo != null) {
        keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
        keyDetails.put("accessToken", tokenInfo.getAccessToken());
        keyDetails.put("tokenDetails", tokenInfo.getJSONString());
    }
    keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, oAuthApplication.getClientId());
    keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, oAuthApplication.getParameter("client_secret"));
    keyDetails.put(APIConstants.FrontEndParameterNames.CLIENT_DETAILS, oAuthApplication.getJsonString());
    keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
    keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.MAPPED.name());
    return keyDetails;
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 45 with KeyManagerConfigurationDTO

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

the class APIConsumerImpl method renewAccessToken.

/**
 * Re-generates the access token.
 *
 * @param oldAccessToken  Token to be revoked
 * @param clientId        Consumer Key for the Application
 * @param clientSecret    Consumer Secret for the Application
 * @param validityTime    Desired Validity time for the token
 * @param requestedScopes Requested Scopes
 * @param jsonInput       Additional parameters if Authorization server needs any.
 * @param keyManagerName  Configured Key Manager
 * @param grantType       Grant Type
 * @return
 * @throws APIManagementException
 */
@Override
public AccessTokenInfo renewAccessToken(String oldAccessToken, String clientId, String clientSecret, String validityTime, String[] requestedScopes, String jsonInput, String keyManagerName, String grantType) throws APIManagementException {
    // Create Token Request with parameters provided from UI.
    AccessTokenRequest tokenRequest = new AccessTokenRequest();
    tokenRequest.setClientId(clientId);
    tokenRequest.setClientSecret(clientSecret);
    tokenRequest.setValidityPeriod(Long.parseLong(validityTime));
    tokenRequest.setTokenToRevoke(oldAccessToken);
    tokenRequest.setScope(requestedScopes);
    tokenRequest.setGrantType(grantType);
    try {
        // Populating additional parameters.
        KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
        String keyManagerTenant = tenantDomain;
        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, keyManagerName);
            if (keyManagerConfiguration == null) {
                throw new APIManagementException("Key Manager " + keyManagerName + " couldn't found.", ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
            }
        }
        if (keyManagerConfiguration.isEnabled()) {
            Object enableTokenGeneration = keyManagerConfiguration.getProperty(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
            if (enableTokenGeneration != null && !(Boolean) enableTokenGeneration) {
                throw new APIManagementException("Key Manager didn't support to generate token Generation From portal", ExceptionCodes.KEY_MANAGER_NOT_SUPPORTED_TOKEN_GENERATION);
            }
            KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerTenant, keyManagerName);
            if (keyManager == null) {
                throw new APIManagementException("Key Manager " + keyManagerName + " not initialized", ExceptionCodes.KEY_MANAGER_INITIALIZATION_FAILED);
            }
            tokenRequest = ApplicationUtils.populateTokenRequest(keyManager, jsonInput, tokenRequest);
            JSONObject appLogObject = new JSONObject();
            appLogObject.put("Re-Generated Keys for application with client Id", clientId);
            APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
            return keyManager.getNewApplicationAccessToken(tokenRequest);
        } else {
            throw new APIManagementException("Key Manager " + keyManagerName + " not enabled", ExceptionCodes.KEY_MANAGER_NOT_ENABLED);
        }
    } catch (APIManagementException e) {
        log.error("Error while re-generating AccessToken", e);
        throw e;
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) 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