use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse in project carbon-apimgt by wso2.
the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithPasswordGrant.
/**
* Test OAuth backend security with password grant type
*/
@Test
public void testOauthBackendSecurityWithPasswordGrant() 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("testID4");
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 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());
Assert.assertNotNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
}
use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse in project carbon-apimgt by wso2.
the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithClientCredentialsGrantWhenTokenExpired.
/**
* Test OAuth backend security with client credentials grant type and when token is expired
*/
@Test
public void testOauthBackendSecurityWithClientCredentialsGrantWhenTokenExpired() 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("testID2");
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 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 setup.
@Before
public void setup() throws ParseException, IOException, APIManagementException {
PowerMockito.spy(TokenCache.class);
tokenCache = TokenCache.getInstance();
PowerMockito.when(TokenCache.getInstance()).thenReturn(tokenCache);
PowerMockito.mockStatic(OAuthClient.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.isRedisEnabled()).thenReturn(false);
latch = new CountDownLatch(1);
// Initialize mock token response.
mockTokenResponse = new TokenResponse();
mockTokenResponse.setAccessToken("testAccessToken");
mockTokenResponse.setTokenType("Bearer");
PowerMockito.when(OAuthClient.generateToken(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyString())).thenReturn(mockTokenResponse);
// Initialize properties of oAuthEndpoint object having common values.
oAuthEndpoint = new OAuthEndpoint();
oAuthEndpoint.setTokenApiUrl("testTokenURL");
oAuthEndpoint.setClientId("testClientID");
oAuthEndpoint.setClientSecret("decryptedClientSecret");
JSONParser parser = new JSONParser();
oAuthEndpoint.setCustomParameters((JSONObject) parser.parse("{}"));
}
use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse in project carbon-apimgt by wso2.
the class AMDefaultKeyManagerImpl method getNewApplicationAccessToken.
@Override
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException {
AccessTokenInfo tokenInfo;
if (tokenRequest == null) {
log.warn("No information available to generate Token.");
return null;
}
// When validity time set to a negative value, a token is considered never to expire.
if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) {
// Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator)
tokenRequest.setValidityPeriod(-2L);
}
// Generate New Access Token
String scopes = String.join(" ", tokenRequest.getScope());
TokenInfo tokenResponse;
try {
String credentials = tokenRequest.getClientId() + ':' + tokenRequest.getClientSecret();
String authToken = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
if (APIConstants.OAuthConstants.TOKEN_EXCHANGE.equals(tokenRequest.getGrantType())) {
tokenResponse = authClient.generate(tokenRequest.getClientId(), tokenRequest.getClientSecret(), tokenRequest.getGrantType(), scopes, (String) tokenRequest.getRequestParam(APIConstants.OAuthConstants.SUBJECT_TOKEN), APIConstants.OAuthConstants.JWT_TOKEN_TYPE);
} else {
tokenResponse = authClient.generate(authToken, GRANT_TYPE_VALUE, scopes);
}
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred while calling token endpoint - " + e.getReason(), e);
}
tokenInfo = new AccessTokenInfo();
if (StringUtils.isNotEmpty(tokenResponse.getScope())) {
tokenInfo.setScope(tokenResponse.getScope().split(" "));
} else {
tokenInfo.setScope(new String[0]);
}
tokenInfo.setAccessToken(tokenResponse.getToken());
tokenInfo.setValidityPeriod(tokenResponse.getExpiry());
return tokenInfo;
}
use of org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse in project carbon-apimgt by wso2.
the class OAuthMediator method mediate.
@Override
public boolean mediate(MessageContext messageContext) {
if (log.isDebugEnabled()) {
log.debug("OAuth Mediator is invoked...");
}
CountDownLatch latch = new CountDownLatch(1);
TokenResponse tokenResponse = null;
if (oAuthEndpoint != null) {
try {
tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
latch.await();
} catch (InterruptedException | APISecurityException e) {
log.error("Could not generate access token...", e);
}
}
if (tokenResponse != null) {
String accessToken = tokenResponse.getAccessToken();
Map<String, Object> transportHeaders = (Map<String, Object>) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty("TRANSPORT_HEADERS");
transportHeaders.put("Authorization", "Bearer " + accessToken);
if (log.isDebugEnabled()) {
log.debug("Access token set: " + GatewayUtils.getMaskedToken(accessToken));
}
} else {
log.debug("Token Response is empty...");
}
messageContext.setProperty(APIMgtGatewayConstants.OAUTH_ENDPOINT_INSTANCE, oAuthEndpoint);
return true;
}
Aggregations