Search in sources :

Example 1 with OAuthEndpoint

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;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) TargetResponse(org.apache.synapse.transport.passthru.TargetResponse) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 2 with OAuthEndpoint

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;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) JSONObject(org.json.simple.JSONObject) CountDownLatch(java.util.concurrent.CountDownLatch) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 3 with OAuthEndpoint

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()));
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with OAuthEndpoint

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());
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 5 with OAuthEndpoint

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("{}"));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder) TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) OAuthEndpoint(org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint) JSONParser(org.json.simple.parser.JSONParser) CountDownLatch(java.util.concurrent.CountDownLatch) Before(org.junit.Before)

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 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)3 OAuthEndpoint (org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)2 JSONObject (org.json.simple.JSONObject)2 JSONParser (org.json.simple.parser.JSONParser)2 ParseException (org.json.simple.parser.ParseException)2 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Map (java.util.Map)1 QName (javax.xml.namespace.QName)1 OMElement (org.apache.axiom.om.OMElement)1 TargetResponse (org.apache.synapse.transport.passthru.TargetResponse)1 Before (org.junit.Before)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder)1