use of org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint in project carbon-apimgt by wso2.
the class OAuthResponseMediator method mediate.
@Override
public boolean mediate(MessageContext messageContext) {
if (messageContext != null) {
TargetResponse targetResponse = (TargetResponse) ((Axis2MessageContext) messageContext).getAxis2MessageContext().getProperty("pass-through.Target-Response");
int statusCode = targetResponse.getStatus();
if (statusCode == 401) {
Object oauthEndpointObject = messageContext.getProperty(APIMgtGatewayConstants.OAUTH_ENDPOINT_INSTANCE);
if (oauthEndpointObject instanceof OAuthEndpoint) {
try {
OAuthTokenGenerator.generateToken((OAuthEndpoint) oauthEndpointObject, null);
log.error("OAuth 2.0 access token has been rejected by the backend...");
handleFailure(APISecurityConstants.OAUTH_TEMPORARY_SERVER_ERROR, messageContext, APISecurityConstants.OAUTH_TEMPORARY_SERVER_ERROR_MESSAGE, "Please try again");
} catch (APISecurityException e) {
log.error("Error when generating oauth 2.0 access token...", e);
}
}
}
}
return true;
}
use of org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint 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;
}
use of org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint 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.conf.OAuthEndpoint 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.conf.OAuthEndpoint 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("{}"));
}
Aggregations