Search in sources :

Example 6 with OAuthEndpoint

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

the class OAuthMediator method init.

@Override
public void init(SynapseEnvironment synapseEnvironment) {
    JSONParser parser = new JSONParser();
    JSONObject customParameterJson = null;
    if (StringUtils.isNotEmpty(customParameters)) {
        try {
            customParameterJson = (JSONObject) parser.parse(customParameters);
        } catch (ParseException e) {
            log.error("Error while parsing custom parameters", e);
        }
    }
    oAuthEndpoint = new OAuthEndpoint();
    oAuthEndpoint.setId(uniqueIdentifier);
    oAuthEndpoint.setTokenApiUrl(tokenEndpointUrl);
    oAuthEndpoint.setClientId(clientId);
    oAuthEndpoint.setClientSecret(clientSecret);
    oAuthEndpoint.setGrantType(grantType);
    oAuthEndpoint.setCustomParameters(customParameterJson);
    if (APIConstants.GRANT_TYPE_PASSWORD.equalsIgnoreCase(grantType)) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            log.warn("User Credentials are empty OAuthMediator will not work properly.");
        } else {
            oAuthEndpoint.setPassword(password.toCharArray());
            oAuthEndpoint.setUsername(username);
        }
    }
}
Also used : JSONObject(org.json.simple.JSONObject) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 7 with OAuthEndpoint

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

the class OAuthTokenGenerator method generateToken.

/**
 * Method to check for and refresh expired/generate new access tokens
 *
 * @param oAuthEndpoint OAuthEndpoint object for token endpoint properties
 * @param latch         CountDownLatch for blocking call when OAuth API is invoked
 * @return TokenResponse object
 * @throws APISecurityException In the event of errors when generating new token
 */
public static TokenResponse generateToken(OAuthEndpoint oAuthEndpoint, CountDownLatch latch) throws APISecurityException {
    try {
        TokenResponse tokenResponse = null;
        if (ServiceReferenceHolder.getInstance().isRedisEnabled()) {
            Object previousResponseObject = new RedisCacheUtils(ServiceReferenceHolder.getInstance().getRedisPool()).getObject(oAuthEndpoint.getId(), TokenResponse.class);
            if (previousResponseObject != null) {
                tokenResponse = (TokenResponse) previousResponseObject;
            }
        } else {
            tokenResponse = TokenCache.getInstance().getTokenMap().get(oAuthEndpoint.getId());
        }
        if (tokenResponse != null) {
            long validTill = tokenResponse.getValidTill();
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long timeDifference = validTill - currentTimeInSeconds;
            if (timeDifference <= 1) {
                if (tokenResponse.getRefreshToken() != null) {
                    tokenResponse = addTokenToCache(oAuthEndpoint, tokenResponse.getRefreshToken());
                } else {
                    tokenResponse = addTokenToCache(oAuthEndpoint, null);
                }
            }
        } else {
            tokenResponse = addTokenToCache(oAuthEndpoint, null);
        }
        return tokenResponse;
    } catch (IOException e) {
        log.error("Error while generating OAuth Token" + getEndpointId(oAuthEndpoint));
        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
    } catch (APIManagementException e) {
        log.error("Could not retrieve OAuth Token" + getEndpointId(oAuthEndpoint));
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, "Error while retrieving OAuth token", e);
    } catch (ParseException e) {
        log.error("Could not retrieve OAuth Token" + getEndpointId(oAuthEndpoint));
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, "Error while parsing OAuth Token endpoint response", e);
    } finally {
        if (latch != null) {
            latch.countDown();
        }
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RedisCacheUtils(org.wso2.carbon.apimgt.gateway.utils.redis.RedisCacheUtils) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException)

Example 8 with OAuthEndpoint

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

the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithPasswordGrantWhenTokenExpired.

/**
 * Test OAuth backend security with password grant type and when token is expired
 */
@Test
public void testOauthBackendSecurityWithPasswordGrantWhenTokenExpired() throws ParseException, IOException, APIManagementException, APISecurityException {
    // Assign values for test specific properties of mock token response and oAuthEndpoint object.
    // expires_in value is subtracted to replicate the token expiry behaviour.
    mockTokenResponse.setExpiresIn("1800");
    long validTill = System.currentTimeMillis() / 1000 - Long.parseLong(mockTokenResponse.getExpiresIn());
    mockTokenResponse.setValidTill(validTill);
    mockTokenResponse.setRefreshToken(null);
    oAuthEndpoint.setId("testID5");
    oAuthEndpoint.setUsername("username");
    oAuthEndpoint.setPassword("password".toCharArray());
    oAuthEndpoint.setGrantType("PASSWORD");
    // 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 is expired, the token endpoint will be called during
    // this operation.
    tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    // Third token generation operation (replicating the behaviour when the mock token response contains a refresh
    // token).
    mockTokenResponse.setRefreshToken("testRefreshToken");
    tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    // Token endpoint will be called three times (during the first, second and third token generation operations).
    PowerMockito.verifyStatic(OAuthClient.class, Mockito.times(3));
    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 9 with OAuthEndpoint

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

the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithPasswordGrantWhenExpiresInNotPresent.

/**
 * Test OAuth backend security with password grant type and when expires_in is not present in the Token Response
 */
@Test
public void testOauthBackendSecurityWithPasswordGrantWhenExpiresInNotPresent() 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("testID6");
    oAuthEndpoint.setUsername("username");
    oAuthEndpoint.setPassword("password".toCharArray());
    oAuthEndpoint.setGrantType("PASSWORD");
    // 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 10 with OAuthEndpoint

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

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