Search in sources :

Example 16 with SubscribedAPI

use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.

the class APIMgtDAOTest method testDeleteSubscriptionsForapiId.

@Test
public void testDeleteSubscriptionsForapiId() throws Exception {
    Subscriber subscriber = new Subscriber("testCreateApplicationRegistrationEntry");
    String organization = "testOrg";
    subscriber.setTenantId(-1234);
    subscriber.setEmail("abc@wso2.com");
    subscriber.setSubscribedDate(new Date(System.currentTimeMillis()));
    apiMgtDAO.addSubscriber(subscriber, null);
    Policy applicationPolicy = getApplicationPolicy("testCreateApplicationRegistrationEntry");
    SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) getSubscriptionPolicy("testCreateApplicationRegistrationEntry");
    subscriptionPolicy.setMonetizationPlan(APIConstants.Monetization.FIXED_RATE);
    apiMgtDAO.addSubscriptionPolicy((SubscriptionPolicy) subscriptionPolicy);
    applicationPolicy.setTenantId(-1234);
    apiMgtDAO.addApplicationPolicy((ApplicationPolicy) applicationPolicy);
    Application application = new Application("testCreateApplicationRegistrationEntry", subscriber);
    application.setTier("testCreateApplicationRegistrationEntry");
    application.setId(apiMgtDAO.addApplication(application, "testCreateApplicationRegistrationEntry", organization));
    application.setDescription("updated description");
    apiMgtDAO.updateApplication(application);
    assertEquals(apiMgtDAO.getApplicationById(application.getId()).getDescription(), "updated description");
    APIIdentifier apiId = new APIIdentifier("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry", "1.0.0");
    API api = new API(apiId);
    api.setContext("/testCreateApplicationRegistrationEntry");
    api.setContextTemplate("/testCreateApplicationRegistrationEntry/{version}");
    api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
    APIPolicy apiPolicy = (APIPolicy) getPolicyAPILevelPerUser("testCreateApplicationRegistrationEntry");
    api.setApiLevelPolicy(apiPolicy.getPolicyName());
    api.setUUID(UUID.randomUUID().toString());
    api.getId().setId(apiMgtDAO.addAPI(api, -1234, organization));
    apiId.setTier(subscriptionPolicy.getPolicyName());
    ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
    int subsId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
    assertTrue(apiMgtDAO.getApplicationsByTier(subscriptionPolicy.getPolicyName()).length > 0);
    String subStatus = apiMgtDAO.getSubscriptionStatusById(subsId);
    assertEquals(subStatus, APIConstants.SubscriptionStatus.ON_HOLD);
    SubscribedAPI subscribedAPI = apiMgtDAO.getSubscriptionById(subsId);
    String clientIdProduction = UUID.randomUUID().toString();
    String clientIdSandbox = UUID.randomUUID().toString();
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_PRODUCTION, application.getId(), clientIdProduction, "Default", UUID.randomUUID().toString());
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_SANDBOX, application.getId(), clientIdSandbox, "Default", UUID.randomUUID().toString());
    assertTrue(apiMgtDAO.getSubscriptionCount(subscriber, application.getName(), null) > 0);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    Mockito.when(keyManager.retrieveApplication(clientIdProduction)).thenReturn(oAuthApplicationInfo);
    Mockito.when(keyManager.retrieveApplication(clientIdSandbox)).thenReturn(oAuthApplicationInfo);
    assertTrue(apiMgtDAO.getSubscribedAPIs(organization, subscriber, null).size() > 0);
    assertEquals(subscribedAPI.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
    assertEquals(subscribedAPI.getApiId(), apiId);
    assertEquals(subscribedAPI.getApplication().getId(), application.getId());
    SubscribedAPI subscribedAPIFromUuid = apiMgtDAO.getSubscriptionByUUID(subscribedAPI.getUUID());
    assertEquals(subscribedAPIFromUuid.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
    assertEquals(subscribedAPIFromUuid.getApiId(), apiId);
    assertEquals(subscribedAPIFromUuid.getApplication().getId(), application.getId());
    apiMgtDAO.updateApplicationStatus(application.getId(), APIConstants.ApplicationStatus.APPLICATION_APPROVED);
    String status = apiMgtDAO.getApplicationStatus("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry");
    assertEquals(status, APIConstants.ApplicationStatus.APPLICATION_APPROVED);
    boolean applicationExist = apiMgtDAO.isApplicationExist(application.getName(), subscriber.getName(), null, organization);
    assertTrue(applicationExist);
    Set<SubscribedAPI> subscribedAPIS = apiMgtDAO.getSubscribedAPIs(subscriber, application.getName(), null);
    assertEquals(subscribedAPIS.size(), 1);
    apiMgtDAO.updateSubscription(apiId, APIConstants.SubscriptionStatus.BLOCKED, application.getId(), organization);
    subscribedAPI.setSubStatus(APIConstants.SubscriptionStatus.REJECTED);
    apiMgtDAO.updateSubscription(subscribedAPI);
    assertTrue(apiMgtDAO.hasSubscription(subscriptionPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_SUB));
    assertTrue(apiMgtDAO.hasSubscription(applicationPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_APP));
    assertTrue(apiMgtDAO.hasSubscription(apiPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_API));
    assertTrue(apiPolicy.getPolicyName().equals(apiMgtDAO.getAPILevelTier(apiMgtDAO.getAPIID(api.getUuid()))));
    apiMgtDAO.recordAPILifeCycleEvent(api.getUuid(), "CREATED", "PUBLISHED", "testCreateApplicationRegistrationEntry", -1234);
    apiMgtDAO.updateDefaultAPIPublishedVersion(apiId);
    apiMgtDAO.removeAllSubscriptions(api.getUuid());
    assertTrue(apiMgtDAO.getAPINamesMatchingContext(api.getContext()).size() > 0);
    apiMgtDAO.deleteAPI(api.getUuid());
    apiMgtDAO.deleteApplication(application);
    apiMgtDAO.removeThrottlePolicy(PolicyConstants.POLICY_LEVEL_APP, "testCreateApplicationRegistrationEntry", -1234);
    apiMgtDAO.deleteApplicationKeyMappingByConsumerKey(clientIdProduction);
    apiMgtDAO.deleteApplicationMappingByConsumerKey(clientIdSandbox);
    deleteSubscriber(subscriber.getId());
}
Also used : QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) Date(java.util.Date) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Application(org.wso2.carbon.apimgt.api.model.Application) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 17 with SubscribedAPI

use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.

the class APIConsumerImpl method removeSubscription.

/**
 * Removes a subscription specified by SubscribedAPI object
 *
 * @param subscription SubscribedAPI object
 * @param organization Organization
 * @throws APIManagementException
 */
@Override
public void removeSubscription(SubscribedAPI subscription, String organization) throws APIManagementException {
    String uuid = subscription.getUUID();
    if (subscription != null) {
        Application application = subscription.getApplication();
        Identifier identifier = subscription.getApiId() != null ? subscription.getApiId() : subscription.getProductId();
        String userId = application.getSubscriber().getName();
        removeSubscription(identifier, userId, application.getId(), organization);
        if (log.isDebugEnabled()) {
            String appName = application.getName();
            String logMessage = "Identifier:  " + identifier.toString() + " subscription (uuid : " + uuid + ") removed from app " + appName;
            log.debug(logMessage);
        }
        // get the workflow state once the executor is executed.
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(application.getId()), WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION);
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
        if (wfDTO != null) {
            if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
                APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
            }
        } else {
            SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_DELETE.name(), tenantId, tenantDomain, subscription.getSubscriptionId(), subscription.getUUID(), identifier.getId(), identifier.getUUID(), application.getId(), application.getUUID(), identifier.getTier(), subscription.getSubStatus());
            APIUtil.sendNotification(subscriptionEvent, APIConstants.NotifierType.SUBSCRIPTIONS.name());
        }
    } else {
        throw new APIManagementException(String.format("Subscription for UUID:%s does not exist.", subscription.getUUID()));
    }
}
Also used : SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 18 with SubscribedAPI

use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.

the class APIProviderImpl method getAPIProductUsageByAPIProductId.

/**
 * Returns usage details of a particular API
 *
 * @param apiProductId API Product identifier
 * @return UserApplicationAPIUsages for given provider
 * @throws org.wso2.carbon.apimgt.api.APIManagementException If failed to get UserApplicationAPIUsage
 */
@Override
public List<SubscribedAPI> getAPIProductUsageByAPIProductId(APIProductIdentifier apiProductId) throws APIManagementException {
    APIProductIdentifier apiIdEmailReplaced = new APIProductIdentifier(APIUtil.replaceEmailDomain(apiProductId.getProviderName()), apiProductId.getName(), apiProductId.getVersion());
    UserApplicationAPIUsage[] allApiProductResult = apiMgtDAO.getAllAPIProductUsageByProvider(apiProductId.getProviderName());
    List<SubscribedAPI> subscribedAPIs = new ArrayList<>();
    for (UserApplicationAPIUsage usage : allApiProductResult) {
        for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) {
            APIProductIdentifier subsApiProductId = apiSubscription.getProductId();
            APIProductIdentifier subsApiProductIdEmailReplaced = new APIProductIdentifier(APIUtil.replaceEmailDomain(subsApiProductId.getProviderName()), subsApiProductId.getName(), subsApiProductId.getVersion());
            if (subsApiProductIdEmailReplaced.equals(apiIdEmailReplaced)) {
                subscribedAPIs.add(apiSubscription);
            }
        }
    }
    return subscribedAPIs;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI)

Example 19 with SubscribedAPI

use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.

the class InternalAPIKeyAuthenticatorTest method testAuthenticateWithExpiredToken.

@Test
public void testAuthenticateWithExpiredToken() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("carbon.super");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn("carbon.super");
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    Cache invalidCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
    JWTTokenPayloadInfo jwtTokenPayloadInfo = new JWTTokenPayloadInfo();
    jwtTokenPayloadInfo.setPayload(signedJWT.getJWTClaimsSet());
    jwtTokenPayloadInfo.setAccessToken(internalKey);
    String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    Mockito.when(internalKeyDataCache.get(cacheKey)).thenReturn(jwtTokenPayloadInfo);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(true);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertFalse(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    Assert.assertEquals(authenticate.getErrorMessage(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
Also used : JWTTokenPayloadInfo(org.wso2.carbon.apimgt.gateway.dto.JWTTokenPayloadInfo) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 20 with SubscribedAPI

use of org.wso2.carbon.apimgt.api.model.SubscribedAPI in project carbon-apimgt by wso2.

the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoCache.

@Test
public void testAuthenticateNoCache() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("carbon.super");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    Cache invalidCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
    Mockito.when(invalidCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    PowerMockito.when(GatewayUtils.verifyTokenSignature(Mockito.any(SignedJWT.class), Mockito.anyString())).thenReturn(true);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(false);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertTrue(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), 0);
    Assert.assertNull(authenticate.getErrorMessage());
    Mockito.verify(internalKeyCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(invalidCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(internalKeyCache, Mockito.times(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "carbon.super");
    Mockito.verify(internalKeyDataCache, Mockito.times(1)).put(Mockito.anyString(), Mockito.any());
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 Application (org.wso2.carbon.apimgt.api.model.Application)28 Tier (org.wso2.carbon.apimgt.api.model.Tier)23 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)16 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)14 ArrayList (java.util.ArrayList)12 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)12 HashSet (java.util.HashSet)11 TreeMap (java.util.TreeMap)11 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)11 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 SQLException (java.sql.SQLException)10 ResultSet (java.sql.ResultSet)9 JSONObject (net.minidev.json.JSONObject)9 API (org.wso2.carbon.apimgt.api.model.API)9