Search in sources :

Example 1 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class GatewayUtils method generateAuthenticationContext.

public static AuthenticationContext generateAuthenticationContext(String jti, JWTValidationInfo jwtValidationInfo, APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String endUserToken, boolean isOauth) {
    AuthenticationContext authContext = new AuthenticationContext();
    authContext.setAuthenticated(true);
    authContext.setApiKey(jti);
    authContext.setUsername(getEndUserFromJWTValidationInfo(jwtValidationInfo, apiKeyValidationInfoDTO));
    authContext.setRequestTokenScopes(jwtValidationInfo.getScopes());
    authContext.setAccessToken(jwtValidationInfo.getRawPayload());
    if (apiKeyValidationInfoDTO != null) {
        authContext.setApiTier(apiKeyValidationInfoDTO.getApiTier());
        authContext.setKeyType(apiKeyValidationInfoDTO.getType());
        authContext.setApplicationId(apiKeyValidationInfoDTO.getApplicationId());
        authContext.setApplicationUUID(apiKeyValidationInfoDTO.getApplicationUUID());
        authContext.setApplicationName(apiKeyValidationInfoDTO.getApplicationName());
        authContext.setApplicationTier(apiKeyValidationInfoDTO.getApplicationTier());
        authContext.setSubscriber(apiKeyValidationInfoDTO.getSubscriber());
        authContext.setTier(apiKeyValidationInfoDTO.getTier());
        authContext.setSubscriberTenantDomain(apiKeyValidationInfoDTO.getSubscriberTenantDomain());
        authContext.setApiName(apiKeyValidationInfoDTO.getApiName());
        authContext.setApiPublisher(apiKeyValidationInfoDTO.getApiPublisher());
        authContext.setStopOnQuotaReach(apiKeyValidationInfoDTO.isStopOnQuotaReach());
        authContext.setSpikeArrestLimit(apiKeyValidationInfoDTO.getSpikeArrestLimit());
        authContext.setSpikeArrestUnit(apiKeyValidationInfoDTO.getSpikeArrestUnit());
        authContext.setConsumerKey(apiKeyValidationInfoDTO.getConsumerKey());
        authContext.setIsContentAware(apiKeyValidationInfoDTO.isContentAware());
        authContext.setGraphQLMaxDepth(apiKeyValidationInfoDTO.getGraphQLMaxDepth());
        authContext.setGraphQLMaxComplexity(apiKeyValidationInfoDTO.getGraphQLMaxComplexity());
    }
    if (isOauth) {
        authContext.setConsumerKey(jwtValidationInfo.getConsumerKey());
        if (jwtValidationInfo.getIssuer() != null) {
            authContext.setIssuer(jwtValidationInfo.getIssuer());
        }
    }
    // Set JWT token sent to the backend
    if (StringUtils.isNotEmpty(endUserToken)) {
        authContext.setCallerToken(endUserToken);
    }
    return authContext;
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)

Example 2 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class GatewayUtils method validateAPISubscription.

/**
 * Validate whether the user is subscribed to the invoked API. If subscribed, return a JSON object containing
 * the API information.
 *
 * @param apiContext API context
 * @param apiVersion API version
 * @param payload    The payload of the JWT token
 * @return an JSON object containing subscribed API information retrieved from token payload.
 * If the subscription information is not found, return a null object.
 * @throws APISecurityException if the user is not subscribed to the API
 */
public static JSONObject validateAPISubscription(String apiContext, String apiVersion, JWTClaimsSet payload, String[] splitToken, boolean isOauth) throws APISecurityException {
    JSONObject api = null;
    APIKeyValidator apiKeyValidator = new APIKeyValidator();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = null;
    boolean apiKeySubValidationEnabled = isAPIKeySubscriptionValidationEnabled();
    JSONObject application;
    int appId = 0;
    if (payload.getClaim(APIConstants.JwtTokenConstants.APPLICATION) != null) {
        application = (JSONObject) payload.getClaim(APIConstants.JwtTokenConstants.APPLICATION);
        appId = Integer.parseInt(application.getAsString(APIConstants.JwtTokenConstants.APPLICATION_ID));
    }
    // if the appId is equal to 0 then it's a internal key
    if (apiKeySubValidationEnabled && appId != 0) {
        apiKeyValidationInfoDTO = apiKeyValidator.validateSubscription(apiContext, apiVersion, appId, getTenantDomain());
    }
    if (payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS) != null) {
        // Subscription validation
        JSONArray subscribedAPIs = (JSONArray) payload.getClaim(APIConstants.JwtTokenConstants.SUBSCRIBED_APIS);
        for (Object subscribedAPI : subscribedAPIs) {
            JSONObject subscribedAPIsJSONObject = (JSONObject) subscribedAPI;
            if (apiContext.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_CONTEXT)) && apiVersion.equals(subscribedAPIsJSONObject.getAsString(APIConstants.JwtTokenConstants.API_VERSION))) {
                // check whether the subscription is authorized
                if (apiKeySubValidationEnabled && appId != 0) {
                    if (apiKeyValidationInfoDTO.isAuthorized()) {
                        api = subscribedAPIsJSONObject;
                        if (log.isDebugEnabled()) {
                            log.debug("User is subscribed to the API: " + apiContext + ", " + "version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
                        }
                    }
                } else {
                    api = subscribedAPIsJSONObject;
                    if (log.isDebugEnabled()) {
                        log.debug("User is subscribed to the API: " + apiContext + ", " + "version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
                    }
                }
                break;
            }
        }
        if (api == null) {
            if (log.isDebugEnabled()) {
                log.debug("User is not subscribed to access the API: " + apiContext + ", version: " + apiVersion + ". Token: " + getMaskedToken(splitToken[0]));
            }
            log.error("User is not subscribed to access the API.");
            throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No subscription information found in the token.");
        }
        // we perform mandatory authentication for Api Keys
        if (!isOauth) {
            log.error("User is not subscribed to access the API.");
            throw new APISecurityException(APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
        }
    }
    return api;
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JSONObject(net.minidev.json.JSONObject) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) JSONArray(net.minidev.json.JSONArray) JSONObject(net.minidev.json.JSONObject) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 3 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testGetKeyValidationInfo.

/*
     * Test method fpr getKeyValidationInfo()
     * */
@Test
public void testGetKeyValidationInfo() throws Exception {
    String context = "/";
    String apiKey = "abc";
    String apiVersion = "1.0";
    String authenticationScheme = "";
    String clientDomain = "abc.com";
    String matchingResource = "/menu";
    String httpVerb = "get";
    boolean defaultVersionInvoked = true;
    APIKeyValidator apiKeyValidator = createAPIKeyValidator(false, getDefaultURITemplates("/menu", "GET"), getDefaultVerbInfoDTO());
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName(apiKey);
    PowerMockito.mockStatic(CacheProvider.class);
    PowerMockito.mockStatic(Cache.class);
    Cache cache = Mockito.mock(Cache.class);
    PowerMockito.mockStatic(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
    PowerMockito.mockStatic(APIManagerConfigurationService.class);
    PowerMockito.mockStatic(CacheProvider.class);
    org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder MockServiceReferenceHolder = Mockito.mock(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.class);
    final APIManagerConfiguration MockApiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance()).thenReturn(MockServiceReferenceHolder);
    APIManagerConfigurationService MockApiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    PowerMockito.when(MockServiceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(MockApiManagerConfigurationService);
    PowerMockito.when(MockApiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(MockApiManagerConfiguration);
    PowerMockito.when(CacheProvider.getDefaultCacheTimeout()).thenReturn((long) 900);
    Mockito.when(CacheProvider.getGatewayKeyCache()).thenReturn(cache);
    Mockito.when(CacheProvider.getResourceCache()).thenReturn(cache);
    Mockito.when(CacheProvider.getGatewayTokenCache()).thenReturn(cache);
    Mockito.when(CacheProvider.getInvalidTokenCache()).thenReturn(cache);
    Assert.assertEquals(apiKeyValidationInfoDTO.getApiName(), apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>()).getApiName());
    // Test for token cache is found in token cache
    AxisConfiguration axisConfig = Mockito.mock(AxisConfiguration.class);
    APIKeyValidator newApiKeyValidator = new APIKeyValidator() {

        @Override
        protected String getTenantDomain() {
            return "zyx";
        }

        @Override
        protected APIManagerConfiguration getApiManagerConfiguration() {
            APIManagerConfiguration configuration = Mockito.mock(APIManagerConfiguration.class);
            Mockito.when(configuration.getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY)).thenReturn("900");
            Mockito.when(configuration.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED)).thenReturn("true");
            return configuration;
        }

        @Override
        protected Cache getCache(String cacheManagerName, String cacheName, long modifiedExp, long accessExp) {
            return Mockito.mock(Cache.class);
        }

        @Override
        protected APIKeyValidationInfoDTO doGetKeyValidationInfo(String context, String apiVersion, String apiKey, String authenticationScheme, String matchingResource, String httpVerb, String tenantDomain, List<String> keyManagers) throws APISecurityException {
            APIKeyValidationInfoDTO apiKeyValidationInfoDTO = Mockito.mock(APIKeyValidationInfoDTO.class);
            Mockito.when(apiKeyValidationInfoDTO.getApiName()).thenReturn(apiKey);
            return apiKeyValidationInfoDTO;
        }
    };
    Assert.assertEquals(apiKeyValidationInfoDTO.getApiName(), newApiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>()).getApiName());
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) ArrayList(java.util.ArrayList) List(java.util.List) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testCheckForValidToken.

// Test for first time invocation for valid token
// Expectation: Token get cached in token cache and @APIKeyValidationInfoDTO cache in key cache
// Neither invalid token cache get called in put/remove
@Test
public void testCheckForValidToken() throws APISecurityException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername("admin");
        String tenantDomain = "carbon.super";
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
        apiKeyValidationInfoDTO.setAuthorized(true);
        AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
        Cache tokenCache = Mockito.mock(Cache.class);
        Cache keyCache = Mockito.mock(Cache.class);
        Cache resourceCache = Mockito.mock(Cache.class);
        Cache invalidTokenCache = Mockito.mock(Cache.class);
        APIKeyDataStore apiKeyDataStore = Mockito.mock(APIKeyDataStore.class);
        APIKeyValidator apiKeyValidator = getAPIKeyValidator(axisConfiguration, invalidTokenCache, tokenCache, keyCache, resourceCache, apiKeyDataStore, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        Mockito.when(tokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(invalidTokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(apiKeyDataStore.getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>())).thenReturn(apiKeyValidationInfoDTO);
        apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>());
        Mockito.verify(tokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).get(Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(1)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(1)).put(Mockito.any(APIKeyValidationInfoDTO.class), Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(apiKeyDataStore, Mockito.times(1)).getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>());
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) WSAPIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.WSAPIKeyDataStore) APIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testCheckForInValidTokenInTenant.

// Test case for Invalid,expired,revoked tokens when first time invocation
// Expectation : invalid token need to put into invalid token cache in tenant and super tenant
@Test
public void testCheckForInValidTokenInTenant() throws APISecurityException {
    try {
        String tenantDomain = "abc.com";
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("abc.com");
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername("admin");
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
        apiKeyValidationInfoDTO.setAuthorized(false);
        apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
        AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
        Cache tokenCache = Mockito.mock(Cache.class);
        Cache keyCache = Mockito.mock(Cache.class);
        Cache resourceCache = Mockito.mock(Cache.class);
        Cache invalidTokenCache = Mockito.mock(Cache.class);
        APIKeyDataStore apiKeyDataStore = Mockito.mock(APIKeyDataStore.class);
        APIKeyValidator apiKeyValidator = getAPIKeyValidator(axisConfiguration, invalidTokenCache, tokenCache, keyCache, resourceCache, apiKeyDataStore, "abc.com");
        Mockito.when(tokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(invalidTokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(apiKeyDataStore.getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>())).thenReturn(apiKeyValidationInfoDTO);
        apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>());
        Mockito.verify(tokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).get(Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).put(Mockito.any(APIKeyValidationInfoDTO.class), Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(2)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(apiKeyDataStore, Mockito.times(1)).getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>());
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) WSAPIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.WSAPIKeyDataStore) APIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)54 Test (org.junit.Test)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)28 Cache (javax.cache.Cache)19 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)14 HashMap (java.util.HashMap)13 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)12 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)12 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)11 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)11 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)11 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)11 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)10 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)9 MessageContext (org.apache.synapse.MessageContext)9 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)9 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)9 SignedJWT (com.nimbusds.jwt.SignedJWT)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 APIKeyDataStore (org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore)7