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