Search in sources :

Example 1 with TokenResponse

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

Example 2 with TokenResponse

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

Example 3 with TokenResponse

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

Example 4 with TokenResponse

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;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TokenInfo(org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo)

Example 5 with TokenResponse

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

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 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 JSONObject (org.json.simple.JSONObject)2 JSONParser (org.json.simple.parser.JSONParser)2 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 Map (java.util.Map)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 ParseException (org.json.simple.parser.ParseException)1 Before (org.junit.Before)1 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder)1 OAuthEndpoint (org.wso2.carbon.apimgt.gateway.mediators.oauth.conf.OAuthEndpoint)1 RedisCacheUtils (org.wso2.carbon.apimgt.gateway.utils.redis.RedisCacheUtils)1 KeyManagerClientException (org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException)1