Search in sources :

Example 6 with TokenResponse

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse in project carbon-apimgt by wso2.

the class OAuthClient method getTokenResponse.

/**
 * Method to retrieve the token response sent from the backend
 * @param response CloseableHttpResponse object
 * @return TokenResponse object containing the details retrieved from the backend
 * @throws APIManagementException In the event of an unexpected HTTP status code from the backend
 * @throws IOException In the event of a problem parsing the response from the backend
 */
private static TokenResponse getTokenResponse(CloseableHttpResponse response) throws APIManagementException, IOException, ParseException {
    int responseCode = response.getStatusLine().getStatusCode();
    if (!(responseCode == HttpStatus.SC_OK)) {
        throw new APIManagementException("Error while accessing the Token URL. " + "Found http status " + response.getStatusLine());
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
    String inputLine;
    StringBuilder stringBuilder = new StringBuilder();
    while ((inputLine = reader.readLine()) != null) {
        stringBuilder.append(inputLine);
    }
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse = (JSONObject) parser.parse(stringBuilder.toString());
    TokenResponse tokenResponse = new TokenResponse();
    if (jsonResponse.containsKey("access_token")) {
        tokenResponse.setAccessToken((String) jsonResponse.get("access_token"));
        if (jsonResponse.containsKey("refresh_token")) {
            tokenResponse.setRefreshToken((String) jsonResponse.get("refresh_token"));
        }
        if (jsonResponse.containsKey("scope")) {
            Set<String> scopeSet = Stream.of(jsonResponse.get("scope").toString().trim().split("\\s*,\\s*")).collect(Collectors.toSet());
            tokenResponse.setScope(scopeSet);
        }
        if (jsonResponse.containsKey("token_type")) {
            tokenResponse.setTokenType((String) jsonResponse.get("token_type"));
        }
        if (jsonResponse.containsKey("expires_in")) {
            tokenResponse.setExpiresIn(jsonResponse.get("expires_in").toString());
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
            tokenResponse.setValidTill(expiryTimeInSeconds);
        } else if (null != APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG)) {
            tokenResponse.setExpiresIn(APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG));
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
            tokenResponse.setValidTill(expiryTimeInSeconds);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Response: [status-code] " + responseCode + " [message] " + stringBuilder.toString());
    }
    if (tokenResponse.getAccessToken() != null) {
        return tokenResponse;
    } else {
        return null;
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) InputStreamReader(java.io.InputStreamReader) JSONObject(org.json.simple.JSONObject) BufferedReader(java.io.BufferedReader) JSONParser(org.json.simple.parser.JSONParser)

Example 7 with TokenResponse

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse 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 TokenResponse

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse 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 TokenResponse

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse 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 TokenResponse

use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse 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 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 JSONObject (org.json.simple.JSONObject)2 JSONParser (org.json.simple.parser.JSONParser)2 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 Map (java.util.Map)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 ParseException (org.json.simple.parser.ParseException)1 Before (org.junit.Before)1 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder)1 OAuthEndpoint (org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint)1 RedisCacheUtils (org.wso2.carbon.apimgt.gateway.utils.redis.RedisCacheUtils)1 KeyManagerClientException (org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException)1