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;
}
}
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();
}
}
}
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());
}
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());
}
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());
}
Aggregations