Search in sources :

Example 11 with OAuthApplicationInfo

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

the class AuthenticatorService method getConsumerKeySecret.

/**
 * This method returns the consumer key & secret of a DCR application.
 *
 * @param appName Name of the DCR application
 * @return Map with consumer key & secret
 * @throws APIManagementException When creating DCR application fails
 */
private Map<String, String> getConsumerKeySecret(String appName) throws APIManagementException {
    HashMap<String, String> consumerKeySecretMap;
    if (!AuthUtil.getConsumerKeySecretMap().containsKey(appName)) {
        consumerKeySecretMap = new HashMap<>();
        List<String> grantTypes = new ArrayList<>();
        grantTypes.add(KeyManagerConstants.PASSWORD_GRANT_TYPE);
        grantTypes.add(KeyManagerConstants.REFRESH_GRANT_TYPE);
        OAuthApplicationInfo oAuthApplicationInfo;
        oAuthApplicationInfo = createDCRApplication(appName, "http://temporary.callback/url", grantTypes);
        consumerKeySecretMap.put(AuthenticatorConstants.CONSUMER_KEY, oAuthApplicationInfo.getClientId());
        consumerKeySecretMap.put(AuthenticatorConstants.CONSUMER_SECRET, oAuthApplicationInfo.getClientSecret());
        AuthUtil.getConsumerKeySecretMap().put(appName, consumerKeySecretMap);
        return consumerKeySecretMap;
    } else {
        return AuthUtil.getConsumerKeySecretMap().get(appName);
    }
}
Also used : OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) ArrayList(java.util.ArrayList)

Example 12 with OAuthApplicationInfo

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

the class AuthenticatorService method createDCRApplication.

/**
 * This method creates a DCR application.
 *
 * @param clientName  Name of the application to be created
 * @param callBackURL Call back URL of the application
 * @param grantTypes  List of grant types of the application
 * @return OAUthApplicationInfo - An object with DCR Application information
 * @throws APIManagementException When creating DCR application fails
 */
private OAuthApplicationInfo createDCRApplication(String clientName, String callBackURL, List<String> grantTypes) throws APIManagementException {
    OAuthApplicationInfo oAuthApplicationInfo;
    try {
        // Here the keyType:"Application" will be passed as a default value
        // for the oAuthAppRequest constructor argument.
        // This value is not related to DCR application creation.
        OAuthAppRequest oAuthAppRequest = new OAuthAppRequest(clientName, callBackURL, AuthenticatorConstants.APPLICATION_KEY_TYPE, grantTypes);
        if (systemApplicationDao.isConsumerKeyExistForApplication(clientName)) {
            String consumerKey = systemApplicationDao.getConsumerKeyForApplication(clientName);
            oAuthApplicationInfo = getKeyManager().retrieveApplication(consumerKey);
        } else {
            oAuthApplicationInfo = getKeyManager().createApplication(oAuthAppRequest);
            if (oAuthApplicationInfo != null) {
                systemApplicationDao.addApplicationKey(clientName, oAuthApplicationInfo.getClientId());
            }
        }
    } catch (KeyManagementException | APIMgtDAOException e) {
        String errorMsg = "Error while creating the keys for OAuth application : " + clientName;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    }
    return oAuthApplicationInfo;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.core.models.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 13 with OAuthApplicationInfo

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

the class AuthenticatorServiceTestCase method testGetAuthenticationConfigurations.

@Test
public void testGetAuthenticationConfigurations() throws Exception {
    // Happy Path - 200
    // // Mocked response object from DCR api
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setCallBackURL("https://localhost/9292/login/callback/store");
    // // Expected data object to be passed to the front-end
    JsonObject oAuthData = new JsonObject();
    String scopes = "apim:self-signup apim:dedicated_gateway apim:subscribe openid";
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationInfo.getClientId());
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationInfo.getCallBackURL());
    oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
    oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, "https://localhost:9080/oauth2/authorize");
    oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, ServiceReferenceHolder.getInstance().getAPIMAppConfiguration().isSsoEnabled());
    oAuthData.addProperty(AuthenticatorConstants.MULTI_ENVIRONMENT_OVERVIEW_ENABLED, APIMConfigurationService.getInstance().getEnvironmentConfigurations().getMultiEnvironmentOverview().isEnabled());
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Get data object to be passed to the front-end
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    JsonObject responseOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseOAuthDataObj, oAuthData);
    // Error Path - 500 - When OAuthApplicationInfo is null
    JsonObject emptyOAuthDataObj = new JsonObject();
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(null);
    JsonObject responseEmptyOAuthDataObj = authenticatorService.getAuthenticationConfigurations("store");
    Assert.assertEquals(responseEmptyOAuthDataObj, emptyOAuthDataObj);
    // Error Path - When DCR application creation fails and throws an APIManagementException
    Mockito.when(keyManager.createApplication(Mockito.any())).thenThrow(KeyManagementException.class);
    try {
        authenticatorService.getAuthenticationConfigurations("store");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while creating the keys for OAuth application : store");
    }
}
Also used : EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) JsonObject(com.google.gson.JsonObject) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Example 14 with OAuthApplicationInfo

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

the class AbstractKeyManager method validateOAuthAppCreationProperties.

protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthApplicationInfo) throws APIManagementException {
    String type = getType();
    List<String> missedRequiredValues = new ArrayList<>();
    KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance().getKeyManagerConnectorConfiguration(type);
    if (keyManagerConnectorConfiguration != null) {
        List<ConfigurationDto> applicationConfigurationDtoList = keyManagerConnectorConfiguration.getApplicationConfigurations();
        Object additionalProperties = oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
        try {
            if (additionalProperties != null) {
                JSONObject additionalPropertiesJson;
                if (additionalProperties instanceof JSONObject) {
                    additionalPropertiesJson = (JSONObject) additionalProperties;
                } else {
                    additionalPropertiesJson = (JSONObject) new JSONParser().parse((String) additionalProperties);
                }
                for (ConfigurationDto configurationDto : applicationConfigurationDtoList) {
                    Object value = additionalPropertiesJson.get(configurationDto.getName());
                    if (value == null) {
                        if (configurationDto.isRequired()) {
                            missedRequiredValues.add(configurationDto.getName());
                        }
                    }
                }
                if (!missedRequiredValues.isEmpty()) {
                    throw new APIManagementException("Missing required properties to create/update oauth " + "application", ExceptionCodes.KEY_MANAGER_MISSING_REQUIRED_PROPERTIES_IN_APPLICATION);
                }
            }
        } catch (ParseException e) {
            throw new APIManagementException("Error while parsing the addition properties of OAuth " + "application");
        }
    } else {
        throw new APIManagementException("Invalid Key Manager Type " + type, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
}
Also used : KeyManagerConnectorConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration) ConfigurationDto(org.wso2.carbon.apimgt.api.model.ConfigurationDto) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 15 with OAuthApplicationInfo

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

the class AbstractKeyManager method buildFromJSON.

/**
 * This method will accept json String and will do the json parse will set oAuth application properties to OAuthApplicationInfo object.
 *
 * @param jsonInput this jsonInput will contain set of oAuth application properties.
 * @return OAuthApplicationInfo object will be return.
 * @throws APIManagementException
 */
public OAuthApplicationInfo buildFromJSON(OAuthApplicationInfo oAuthApplicationInfo, String jsonInput) throws APIManagementException {
    // initiate json parser.
    JSONParser parser = new JSONParser();
    JSONObject jsonObject;
    try {
        // parse json String
        jsonObject = (JSONObject) parser.parse(jsonInput);
        if (jsonObject != null) {
            // create a map to hold json parsed objects.
            Map<String, Object> params = (Map) jsonObject;
            if (params.get(APIConstants.JSON_CALLBACK_URL) != null) {
                oAuthApplicationInfo.setCallBackURL((String) params.get(APIConstants.JSON_CALLBACK_URL));
            }
            if (params.get(APIConstants.JSON_GRANT_TYPES) != null) {
                String grantTypeString = params.get(APIConstants.JSON_GRANT_TYPES).toString();
                if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL()) && (grantTypeString.contains("implicit") || grantTypeString.contains("authorization_code"))) {
                    throw new EmptyCallbackURLForCodeGrantsException("The callback url must have at least one URI " + "value when using Authorization code or implicit grant types.");
                }
            }
            // set client Id
            if (params.get(APIConstants.JSON_CLIENT_ID) != null) {
                oAuthApplicationInfo.setClientId((String) params.get(APIConstants.JSON_CLIENT_ID));
            }
            // set client secret
            if (params.get(APIConstants.JSON_CLIENT_SECRET) != null) {
                oAuthApplicationInfo.setClientSecret((String) params.get(APIConstants.JSON_CLIENT_SECRET));
            }
            // copy all params map in to OAuthApplicationInfo's Map object.
            oAuthApplicationInfo.putAll(params);
            validateOAuthAppCreationProperties(oAuthApplicationInfo);
            return oAuthApplicationInfo;
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON String", e);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) EmptyCallbackURLForCodeGrantsException(org.wso2.carbon.apimgt.api.EmptyCallbackURLForCodeGrantsException)

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