Search in sources :

Example 11 with OAuthEndpoint

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint 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 12 with OAuthEndpoint

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint in project carbon-apimgt by wso2.

the class APIManagerConfiguration method setRecommendationConfigurations.

/**
 * To populate recommendation related configurations
 *
 * @param element
 */
private void setRecommendationConfigurations(OMElement element) {
    OMElement recommendationSeverEndpointElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_ENDPOINT));
    if (recommendationSeverEndpointElement != null) {
        recommendationEnvironment = new RecommendationEnvironment();
        String recommendationSeverEndpoint = recommendationSeverEndpointElement.getText();
        recommendationEnvironment.setRecommendationServerURL(recommendationSeverEndpoint);
        OMElement consumerKeyElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_KEY));
        if (consumerKeyElement != null) {
            if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerKey")) {
                recommendationEnvironment.setConsumerKey(secretResolver.resolve("APIManager.Recommendations.ConsumerKey"));
            } else {
                recommendationEnvironment.setConsumerKey(consumerKeyElement.getText());
            }
            OMElement consumerSecretElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_API_CONSUMER_SECRET));
            if (consumerSecretElement != null) {
                if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.ConsumerSecret")) {
                    recommendationEnvironment.setConsumerSecret(secretResolver.resolve("APIManager.Recommendations.ConsumerSecret"));
                } else {
                    recommendationEnvironment.setConsumerSecret(consumerSecretElement.getText());
                }
                OMElement oauthEndpointElement = element.getFirstChildWithName(new QName(APIConstants.AUTHENTICATION_ENDPOINT));
                String oauthEndpoint = null;
                if (oauthEndpointElement != null) {
                    oauthEndpoint = oauthEndpointElement.getText();
                } else {
                    try {
                        URL endpointURL = new URL(recommendationSeverEndpoint);
                        oauthEndpoint = endpointURL.getProtocol() + "://" + endpointURL.getHost() + ":" + endpointURL.getPort();
                    } catch (MalformedURLException e) {
                        log.error("Error when reading the recommendationServer Endpoint", e);
                    }
                }
                // Oauth URL is set only if both consumer key
                recommendationEnvironment.setOauthURL(oauthEndpoint);
            // and consumer secrets are correctly defined
            }
        }
        OMElement applyForAllTenantsElement = element.getFirstChildWithName(new QName(APIConstants.APPLY_RECOMMENDATIONS_FOR_ALL_APIS));
        if (applyForAllTenantsElement != null) {
            recommendationEnvironment.setApplyForAllTenants(JavaUtils.isTrueExplicitly(applyForAllTenantsElement.getText()));
        } else {
            log.debug("Apply For All Tenants Element is not set. Set to default true");
        }
        OMElement maxRecommendationsElement = element.getFirstChildWithName(new QName(APIConstants.MAX_RECOMMENDATIONS));
        if (maxRecommendationsElement != null) {
            recommendationEnvironment.setMaxRecommendations(Integer.parseInt(maxRecommendationsElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
        OMElement userNameElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_USERNAME));
        if (userNameElement != null) {
            recommendationEnvironment.setUserName(userNameElement.getText());
            log.debug("Basic OAuth used for recommendation server");
        }
        OMElement passwordElement = element.getFirstChildWithName(new QName(APIConstants.RECOMMENDATION_PASSWORD));
        if (passwordElement != null) {
            if (secretResolver.isInitialized() && secretResolver.isTokenProtected("APIManager.Recommendations.password")) {
                recommendationEnvironment.setPassword(secretResolver.resolve("APIManager.Recommendations.password"));
            } else {
                recommendationEnvironment.setPassword(passwordElement.getText());
            }
        }
        OMElement waitDurationElement = element.getFirstChildWithName(new QName(APIConstants.WAIT_DURATION));
        if (waitDurationElement != null) {
            recommendationEnvironment.setWaitDuration(Long.parseLong(waitDurationElement.getText()));
        } else {
            log.debug("Max recommendations is not set. Set to default 5");
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) URL(java.net.URL)

Aggregations

TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)9 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)3 OAuthEndpoint (org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)2 JSONObject (org.json.simple.JSONObject)2 JSONParser (org.json.simple.parser.JSONParser)2 ParseException (org.json.simple.parser.ParseException)2 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Map (java.util.Map)1 QName (javax.xml.namespace.QName)1 OMElement (org.apache.axiom.om.OMElement)1 TargetResponse (org.apache.synapse.transport.passthru.TargetResponse)1 Before (org.junit.Before)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder)1