Search in sources :

Example 16 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project product-iots by wso2.

the class QSGUtils method initConfig.

public static EMMQSGConfig initConfig() {
    Properties props = new Properties();
    InputStream input = null;
    EMMQSGConfig emmConfig = null;
    try {
        input = new FileInputStream("config.properties");
        // load a properties file and set the properties
        props.load(input);
        emmConfig = EMMQSGConfig.getInstance();
        emmConfig.setEmmHost(props.getProperty("emm-host"));
        emmConfig.setDcrEndPoint(props.getProperty("dcr-endpoint"));
        emmConfig.setOauthEndPoint(props.getProperty("oauth-endpoint"));
        emmConfig.setUsername(props.getProperty("username"));
        emmConfig.setPassword(props.getProperty("password"));
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return emmConfig;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) EMMQSGConfig(org.wso2.mdm.qsg.dto.EMMQSGConfig) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream)

Example 17 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project product-iots by wso2.

the class QSGExecutor method main.

public static void main(String[] args) {
    boolean status = false;
    // prompt for the user's name
    /*
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your email address and press enter : ");
        String email = scanner.next();
        if (!QSGUtils.isValidEmailAddress(email)) {
            do {
                System.out.print("Please enter a valid email address and press enter : ");
                email = scanner.next();
            } while (!QSGUtils.isValidEmailAddress(email));
        }
        */
    String email = "alex@example.com";
    // Setup the OAuth token
    String token = QSGUtils.getOAuthToken();
    if (token == null) {
        System.out.println("Unable to get the OAuth token. Please check the config.properties file.");
        System.exit(0);
    }
    HTTPInvoker.oAuthToken = token;
    // Creates the admin user
    System.out.println("Creating users ");
    status = UserOperations.createUser(iotAdminUser, iotAdminEmail, true);
    if (!status) {
        System.out.println("Unable to create the admin user. Please check the config.properties file.");
        System.exit(0);
    }
    status = UserOperations.changePassword(iotAdminUser, iotAdminPassword);
    if (!status) {
        System.out.println("Unable to change the password of the admin user. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    // Creates the emm user
    status = UserOperations.createUser(iotMobileUser, email, false);
    if (!status) {
        System.out.println("Unable to create the iot user ryan. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    status = UserOperations.changePassword(iotMobileUser, iotMobileUserPassword);
    if (!status) {
        System.out.println("Unable to change the password of the iot user. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    // Creates the emm-user role
    System.out.println("Creating iotMobileUser role");
    status = UserOperations.createRole(roleName, new String[] { iotMobileUser });
    if (!status) {
        System.out.println("Unable to create the emm user role. Terminating the IoTs QSG now.");
        System.exit(0);
    }
    System.out.println("Adding sample policies ");
    // Add the android policy
    status = PolicyOperations.createPasscodePolicy("android-passcode-policy1", Constants.DeviceType.ANDROID);
    if (!status) {
        System.out.println("Unable to create the android passcode policy. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    // Add the windows policy
    status = PolicyOperations.createPasscodePolicy("windows-passcode-policy1", Constants.DeviceType.WINDOWS);
    if (!status) {
        System.out.println("Unable to create the windows passcode policy. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    System.out.println("Upload the android application ");
    // Upload the android application
    MobileApplication application = AppOperations.uploadApplication(Constants.DeviceType.ANDROID, "con-app.apk", "application/vnd.android.package-archive");
    if (application == null) {
        System.out.println("Unable to upload the sample android application. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    // Upload the assets
    application = AppOperations.uploadAssets(Constants.DeviceType.ANDROID, application);
    if (application == null) {
        System.out.println("Unable to upload the assets for sample android application. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    System.out.println("Create the android application ");
    // Create application entry in publisher
    status = AppOperations.addApplication("WSO2Con-Android", application, true);
    if (!status) {
        System.out.println("Unable to create the android mobile application. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    System.out.println("Upload the iOS application ");
    // Add the iOS policy
    status = PolicyOperations.createPasscodePolicy("ios-passcode-policy1", Constants.DeviceType.IOS);
    if (!status) {
        System.out.println("Unable to create the ios passcode policy. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    // Upload the ios application
    MobileApplication iOSApplication = AppOperations.uploadApplication(Constants.DeviceType.IOS, "PNDemo.ipa", "application/octet-stream");
    iOSApplication.setVersion("1.0.0");
    // Upload the assets
    iOSApplication = AppOperations.uploadAssets(Constants.DeviceType.IOS, iOSApplication);
    if (iOSApplication == null) {
        System.out.println("Unable to upload the assets for sample iOS application. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    System.out.println("Create the iOS application ");
    // Create application entry in publisher
    status = AppOperations.addApplication("WSO2Con-iOS", iOSApplication, true);
    if (!status) {
        System.out.println("Unable to create the iOS mobile application. Terminating the IoTS QSG now.");
        System.exit(0);
    }
    System.out.println("Exit");
}
Also used : MobileApplication(org.wso2.mdm.qsg.dto.MobileApplication)

Example 18 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth 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 19 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth 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)

Example 20 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method setOAuthApplicationInfo.

/**
 * set information that are needed to invoke callback service
 */
private void setOAuthApplicationInfo(APIStateWorkflowDTO apiStateWorkFlowDTO) throws WorkflowException {
    // if credentials are not defined in the workflow-extension.xml file call dcr endpoint and generate a
    // oauth application and pass the client id and secret
    WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (clientId == null || clientSecret == null) {
        String dcrUsername = workflowProperties.getdCREndpointUser();
        String dcrPassword = workflowProperties.getdCREndpointPassword();
        byte[] encodedAuth = Base64.encodeBase64((dcrUsername + ":" + dcrPassword).getBytes(Charset.forName("ISO-8859-1")));
        JSONObject payload = new JSONObject();
        payload.put(PayloadConstants.KEY_OAUTH_APPNAME, WorkflowConstants.WORKFLOW_OAUTH_APP_NAME);
        payload.put(PayloadConstants.KEY_OAUTH_OWNER, dcrUsername);
        payload.put(PayloadConstants.KEY_OAUTH_SAASAPP, "true");
        payload.put(PayloadConstants.KEY_OAUTH_GRANT_TYPES, WorkflowConstants.WORKFLOW_OAUTH_APP_GRANT_TYPES);
        URL serviceEndpointURL = new URL(workflowProperties.getdCREndPoint());
        HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
        HttpPost httpPost = new HttpPost(workflowProperties.getdCREndPoint());
        String authHeader = "Basic " + new String(encodedAuth);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        StringEntity requestEntity = new StringEntity(payload.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                String responseStr = EntityUtils.toString(entity);
                if (log.isDebugEnabled()) {
                    log.debug("Workflow oauth app created: " + responseStr);
                }
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse(responseStr);
                clientId = (String) obj.get(PayloadConstants.VARIABLE_CLIENTID);
                clientSecret = (String) obj.get(PayloadConstants.VARIABLE_CLIENTSECRET);
            } else {
                String error = "Error while starting the process:  " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
                log.error(error);
                throw new WorkflowException(error);
            }
        } catch (ClientProtocolException e) {
            String errorMsg = "Error while creating the http client";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = "Error while connecting to dcr endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (ParseException e) {
            String errorMsg = "Error while parsing response from DCR endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } finally {
            httpPost.reset();
        }
    }
    apiStateWorkFlowDTO.setClientId(clientId);
    apiStateWorkFlowDTO.setClientSecret(clientSecret);
    apiStateWorkFlowDTO.setScope(WorkflowConstants.API_WF_SCOPE);
    apiStateWorkFlowDTO.setTokenAPI(workflowProperties.getTokenEndPoint());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5