Search in sources :

Example 26 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithClientCredentialsGrantWhenExpiresInNotPresent.

/**
 * Test OAuth backend security with client credentials grant type and when expires_in is not present in the
 * Token Response
 */
@Test
public void testOauthBackendSecurityWithClientCredentialsGrantWhenExpiresInNotPresent() throws ParseException, IOException, APIManagementException, APISecurityException {
    // Assign values for test specific properties of oAuthEndpoint object. expires_in and validTill properties will
    // be null in the mock token response.
    mockTokenResponse.setRefreshToken("testRefreshToken");
    oAuthEndpoint.setId("testID3");
    oAuthEndpoint.setGrantType("CLIENT_CREDENTIALS");
    // First token generation operation. Token endpoint will be called and the token response will not be cached.
    TokenResponse tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    Assert.assertNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
    // Second token generation operation. Since the token response was not cached, the token endpoint will be
    // called during this operation.
    tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    // Token endpoint will be called two times (during the first and second token generation operations).
    PowerMockito.verifyStatic(OAuthClient.class, Mockito.times(2));
    OAuthClient.generateToken(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyString());
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 27 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithClientCredentialsGrant.

/**
 * Test OAuth backend security with client credentials grant type
 */
@Test
public void testOauthBackendSecurityWithClientCredentialsGrant() throws ParseException, IOException, APIManagementException, APISecurityException {
    // Assign values for test specific properties of mock token response and oAuthEndpoint object.
    mockTokenResponse.setExpiresIn("1800");
    long validTill = System.currentTimeMillis() / 1000 + Long.parseLong(mockTokenResponse.getExpiresIn());
    mockTokenResponse.setValidTill(validTill);
    mockTokenResponse.setRefreshToken("testRefreshToken");
    oAuthEndpoint.setId("testID1");
    oAuthEndpoint.setGrantType("CLIENT_CREDENTIALS");
    // First token generation operation. Token endpoint will be called and the token response will be cached.
    TokenResponse tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    Assert.assertNotNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
    // Second token generation operation. Since the token response was cached, the token endpoint will not be
    // called during this operation.
    tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    // Token endpoint will be called only one time (during the first token generation operation).
    PowerMockito.verifyStatic(OAuthClient.class, Mockito.times(1));
    OAuthClient.generateToken(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyString());
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 28 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIUtil method getExternalStores.

/**
 * Returns a set of External API Stores as defined in the underlying governance
 * registry.
 *
 * @return a Map of tier names and Tier objects - possibly empty
 * @throws APIManagementException if an error occurs when loading tiers from the registry
 */
public static Set<APIStore> getExternalStores(int tenantId) throws APIManagementException {
    // First checking if ExternalStores are defined in api-manager.xml
    Set<APIStore> externalAPIStores = getGlobalExternalStores();
    // If defined, return Store Config provided there.
    if (externalAPIStores != null && !externalAPIStores.isEmpty()) {
        return externalAPIStores;
    }
    // Else Read the config from Tenant's Registry.
    externalAPIStores = new HashSet<>();
    try {
        Iterator apiStoreIterator = getExternalStoresIteratorFromConfig(tenantId);
        if (apiStoreIterator != null) {
            while (apiStoreIterator.hasNext()) {
                APIStore store = new APIStore();
                OMElement storeElem = (OMElement) apiStoreIterator.next();
                String type = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_TYPE));
                String className = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_CLASS_NAME));
                store.setPublisher((APIPublisher) getClassInstance(className));
                // Set Store type [eg:wso2]
                store.setType(type);
                String name = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_ID));
                if (name == null) {
                    log.error("The ExternalAPIStore name attribute is not defined in external-api-stores.xml.");
                }
                // Set store name
                store.setName(name);
                OMElement configDisplayName = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_DISPLAY_NAME));
                String displayName = (configDisplayName != null) ? replaceSystemProperty(configDisplayName.getText()) : name;
                // Set store display name
                store.setDisplayName(displayName);
                store.setEndpoint(replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_ENDPOINT)).getText()));
                // Set store endpoint, which is used to publish APIs
                store.setPublished(false);
                if (APIConstants.WSO2_API_STORE_TYPE.equals(type)) {
                    OMElement password = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_PASSWORD));
                    if (password != null) {
                        String value = password.getText();
                        PasswordResolver passwordResolver = PasswordResolverFactory.getInstance();
                        store.setPassword(replaceSystemProperty(passwordResolver.getPassword(value)));
                        store.setUsername(replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_USERNAME)).getText()));
                    // Set store login username
                    } else {
                        log.error("The user-credentials of API Publisher is not defined in the <ExternalAPIStore> " + "config of external-api-stores.xml.");
                    }
                }
                externalAPIStores.add(store);
            }
        }
    } catch (ClassNotFoundException e) {
        String msg = "One or more classes defined in APIConstants.EXTERNAL_API_STORE_CLASS_NAME cannot be found";
        throw new APIManagementException(msg, e);
    } catch (InstantiationException e) {
        String msg = "One or more classes defined in APIConstants.EXTERNAL_API_STORE_CLASS_NAME cannot be load";
        throw new APIManagementException(msg, e);
    } catch (IllegalAccessException e) {
        String msg = "One or more classes defined in APIConstants.EXTERNAL_API_STORE_CLASS_NAME cannot be access";
        throw new APIManagementException(msg, e);
    }
    return externalAPIStores;
}
Also used : PasswordResolver(org.wso2.carbon.apimgt.api.PasswordResolver) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) QName(javax.xml.namespace.QName) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) OMElement(org.apache.axiom.om.OMElement) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 29 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method getBasicAuthHeader.

/**
 * get credentials that are needed to call the rest api in BPMN engine
 */
private String getBasicAuthHeader() {
    // api-manager.xml configuration
    if (username == null || password == null) {
        WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
        username = workflowProperties.getServerUser();
        password = workflowProperties.getServerPassword();
    }
    byte[] encodedAuth = Base64.encodeBase64((username + ":" + password).getBytes(Charset.forName("ISO-8859-1")));
    return "Basic " + new String(encodedAuth);
}
Also used : WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)

Example 30 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method execute.

@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing API State change Workflow.");
        log.debug("Execute workflowDTO " + workflowDTO.toString());
    }
    if (stateList != null) {
        Map<String, List<String>> stateActionMap = getSelectedStatesToApprove();
        APIStateWorkflowDTO apiStateWorkFlowDTO = (APIStateWorkflowDTO) workflowDTO;
        if (stateActionMap.containsKey(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase()) && stateActionMap.get(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase()).contains(apiStateWorkFlowDTO.getApiLCAction())) {
            // set the auth application related info. This will be used to call the callback service
            setOAuthApplicationInfo(apiStateWorkFlowDTO);
            // build request payload
            String jsonPayload = buildPayloadForBPMNProcess(apiStateWorkFlowDTO);
            if (log.isDebugEnabled()) {
                log.debug("APIStateChange payload: " + jsonPayload);
            }
            if (serviceEndpoint == null) {
                // set the bps endpoint from the global configurations
                WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
                serviceEndpoint = workflowProperties.getServerUrl();
            }
            URL serviceEndpointURL = new URL(serviceEndpoint);
            HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
            HttpPost httpPost = new HttpPost(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH);
            // Generate the basic auth header using provided user credentials
            String authHeader = getBasicAuthHeader();
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
            StringEntity requestEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);
            try {
                HttpResponse response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                    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 the BPMN process server from the WorkflowExecutor.";
                log.error(errorMsg, e);
                throw new WorkflowException(errorMsg, e);
            } finally {
                httpPost.reset();
            }
            super.execute(workflowDTO);
        } else {
            // For any other states, act as simpleworkflow executor.
            workflowDTO.setStatus(WorkflowStatus.APPROVED);
            // calling super.complete() instead of complete() to act as the simpleworkflow executor
            super.complete(workflowDTO);
        }
    } else {
        String msg = "State change list is not provided. Please check <stateList> element in ";
        log.error(msg);
        throw new WorkflowException(msg);
    }
    return new GeneralWorkflowResponse();
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) 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) HttpClient(org.apache.http.client.HttpClient) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 HttpClient (org.apache.http.client.HttpClient)12 URL (java.net.URL)10 ArrayList (java.util.ArrayList)9 HttpGet (org.apache.http.client.methods.HttpGet)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 HttpResponse (org.apache.http.HttpResponse)8 Gson (com.google.gson.Gson)6 JSONObject (org.json.simple.JSONObject)6 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Test (org.testng.annotations.Test)6 Response (feign.Response)4 WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)4 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)3 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)3 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)3