Search in sources :

Example 1 with JWTValidationService

use of org.wso2.carbon.apimgt.impl.jwt.JWTValidationService in project carbon-apimgt by wso2.

the class APIManagerComponent method activate.

@Activate
protected void activate(ComponentContext componentContext) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("API manager component activated");
    }
    try {
        BundleContext bundleContext = componentContext.getBundleContext();
        addRxtConfigs();
        addApplicationsPermissionsToRegistry();
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        String filePath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "api-manager.xml";
        configuration.load(filePath);
        String gatewayType = configuration.getFirstProperty(APIConstants.API_GATEWAY_TYPE);
        if (APIConstants.API_GATEWAY_TYPE_SYNAPSE.equalsIgnoreCase(gatewayType)) {
            addDefinedSequencesToRegistry();
        }
        CommonConfigDeployer configDeployer = new CommonConfigDeployer();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), configDeployer, null);
        TenantLoadMessageSender tenantLoadMessageSender = new TenantLoadMessageSender();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), tenantLoadMessageSender, null);
        KeyMgtConfigDeployer keyMgtConfigDeployer = new KeyMgtConfigDeployer();
        bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(), keyMgtConfigDeployer, null);
        // Registering Notifiers
        bundleContext.registerService(Notifier.class.getName(), new SubscriptionsNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ApisNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ApplicationNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ApplicationRegistrationNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new PolicyNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new DeployAPIInGatewayNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ScopesNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new CertificateNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new GoogleAnalyticsNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ExternalGatewayNotifier(), null);
        bundleContext.registerService(Notifier.class.getName(), new ExternallyDeployedApiNotifier(), null);
        APIManagerConfigurationServiceImpl configurationService = new APIManagerConfigurationServiceImpl(configuration);
        ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(configurationService);
        APIMgtDBUtil.initialize();
        APIMConfigService apimConfigService = new APIMConfigServiceImpl();
        bundleContext.registerService(APIMConfigService.class.getName(), apimConfigService, null);
        APIUtil.loadAndSyncTenantConf(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadTenantExternalStoreConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadTenantGAConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadTenantWorkFlowExtensions(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        // load self sigup configuration to the registry
        APIUtil.loadTenantSelfSignUpConfigurations(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIUtil.loadCommonOperationPolicies(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        APIManagerAnalyticsConfiguration analyticsConfiguration = APIManagerAnalyticsConfiguration.getInstance();
        analyticsConfiguration.setAPIManagerConfiguration(configuration);
        registration = componentContext.getBundleContext().registerService(APIManagerConfigurationService.class.getName(), configurationService, null);
        KeyManagerConfigurationServiceImpl keyManagerConfigurationService = new KeyManagerConfigurationServiceImpl();
        registration = componentContext.getBundleContext().registerService(KeyManagerConfigurationService.class, keyManagerConfigurationService, null);
        JWTValidationService jwtValidationService = new JWTValidationServiceImpl();
        registration = componentContext.getBundleContext().registerService(JWTValidationService.class, jwtValidationService, null);
        ServiceReferenceHolder.getInstance().setKeyManagerConfigurationService(keyManagerConfigurationService);
        APIStatusObserverList.getInstance().init(configuration);
        log.debug("Reading Analytics Configuration from file...");
        // This method is called in two places. Mostly by the time activate hits,
        // ServiceDataPublisherAdmin is not activated. Therefore, this same method is run,
        // when ServiceDataPublisherAdmin is set.
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_GOVERNANCE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + "/trunk"), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_APIMGT_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_APPLICATION_DATA_LOCATION), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
        // Enabling API Publishers/Creators to make changes on life-cycle history.
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_CREATOR_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION, null);
        AuthorizationUtils.addAuthorizeRoleListener(APIConstants.AM_PUBLISHER_LIFECYCLE_EXECUTION_ID, RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.API_LIFE_CYCLE_HISTORY), APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION, null);
        setupImagePermissions();
        GatewayArtifactsMgtDBUtil.initialize();
        configureEventPublisherProperties();
        configureNotificationEventPublisher();
        // Load initially available api contexts at the server startup. This Cache is only use by the products other than the api-manager
        /* TODO: Load Config values from apimgt.core*/
        boolean apiManagementEnabled = APIUtil.isAPIManagementEnabled();
        boolean loadAPIContextsAtStartup = APIUtil.isLoadAPIContextsAtStartup();
        if (apiManagementEnabled && loadAPIContextsAtStartup) {
            List<String> contextList = ApiMgtDAO.getInstance().getAllAvailableContexts();
            Cache contextCache = APIUtil.getAPIContextCache();
            for (String context : contextList) {
                contextCache.put(context, Boolean.TRUE);
            }
        }
        try {
            APIUtil.createDefaultRoles(MultitenantConstants.SUPER_TENANT_ID);
        } catch (APIManagementException e) {
            log.error("Failed create default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
        } catch (Exception e) {
            // The generic Exception is handled explicitly so execution does not stop during config deployment
            log.error("Exception when creating default roles for tenant " + MultitenantConstants.SUPER_TENANT_ID, e);
        }
        // Adding default throttle policies
        addDefaultAdvancedThrottlePolicies();
        // Update all NULL THROTTLING_TIER values to Unlimited
        boolean isNullThrottlingTierConversionEnabled = APIUtil.updateNullThrottlingTierAtStartup();
        try {
            if (isNullThrottlingTierConversionEnabled) {
                ApiMgtDAO.getInstance().convertNullThrottlingTiers();
            }
        } catch (APIManagementException e) {
            log.error("Failed to convert NULL THROTTLING_TIERS to Unlimited");
        }
        // // Initialise KeyManager.
        // KeyManagerHolder.initializeKeyManager(configuration);
        // Initialise sql constants
        SQLConstantManagerFactory.initializeSQLConstantManager();
        // Initialize PasswordResolver
        PasswordResolverFactory.initializePasswordResolver();
        APIUtil.init();
        // Activating UserPostSelfRegistration handler componeAPITemplateBuilderImplnt
        try {
            registration = componentContext.getBundleContext().registerService(AbstractEventHandler.class.getName(), new UserPostSelfRegistrationHandler(), null);
        } catch (Exception e) {
            log.error("Error while activating UserPostSelfRegistration handler component.", e);
        }
        // Read the trust store
        ServerConfiguration config = CarbonUtils.getServerConfiguration();
        // Initialize product REST API token caches
        CacheProvider.createRESTAPITokenCache();
        CacheProvider.createRESTAPIInvalidTokenCache();
        CacheProvider.createGatewayJWTTokenCache();
        CacheProvider.createTenantConfigCache();
        CacheProvider.createRecommendationsCache();
        CacheProvider.createParsedSignJWTCache();
        CacheProvider.createGatewayBasicAuthResourceCache();
        CacheProvider.createGatewayUsernameCache();
        CacheProvider.createIntrospectionCache();
        // Initialize Recommendation wso2event output publisher
        configureRecommendationEventPublisherProperties();
        setupAccessTokenGenerator();
        retrieveAndSetParentTrustStore();
        if (configuration.getGatewayArtifactSynchronizerProperties().isRetrieveFromStorageEnabled()) {
            if (APIConstants.GatewayArtifactSynchronizer.DB_RETRIEVER_NAME.equals(configuration.getGatewayArtifactSynchronizerProperties().getRetrieverName())) {
                bundleContext.registerService(ArtifactRetriever.class.getName(), new DBRetriever(), null);
            }
        }
        bundleContext.registerService(ScopeValidator.class, new SystemScopesIssuer(), null);
    } catch (APIManagementException e) {
        log.error("Error while initializing the API manager component", e);
    } catch (APIManagerDatabaseException e) {
        log.fatal("Error while Creating the database", e);
    }
}
Also used : CertificateNotifier(org.wso2.carbon.apimgt.impl.notifier.CertificateNotifier) ExternalGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternalGatewayNotifier) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) ApplicationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationNotifier) APIManagerDatabaseException(org.wso2.carbon.apimgt.api.APIManagerDatabaseException) KeyManagerConfigurationServiceImpl(org.wso2.carbon.apimgt.impl.keymgt.KeyManagerConfigurationServiceImpl) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerConfigurationService(org.wso2.carbon.apimgt.impl.keymgt.KeyManagerConfigurationService) SubscriptionsNotifier(org.wso2.carbon.apimgt.impl.notifier.SubscriptionsNotifier) DBRetriever(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.DBRetriever) KeyMgtConfigDeployer(org.wso2.carbon.apimgt.impl.observers.KeyMgtConfigDeployer) ApplicationRegistrationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationRegistrationNotifier) ExternallyDeployedApiNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternallyDeployedApiNotifier) GoogleAnalyticsNotifier(org.wso2.carbon.apimgt.impl.notifier.GoogleAnalyticsNotifier) SubscriptionsNotifier(org.wso2.carbon.apimgt.impl.notifier.SubscriptionsNotifier) PolicyNotifier(org.wso2.carbon.apimgt.impl.notifier.PolicyNotifier) ApplicationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationNotifier) Notifier(org.wso2.carbon.apimgt.impl.notifier.Notifier) ScopesNotifier(org.wso2.carbon.apimgt.impl.notifier.ScopesNotifier) DeployAPIInGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.DeployAPIInGatewayNotifier) CertificateNotifier(org.wso2.carbon.apimgt.impl.notifier.CertificateNotifier) ExternalGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternalGatewayNotifier) ApisNotifier(org.wso2.carbon.apimgt.impl.notifier.ApisNotifier) ExternallyDeployedApiNotifier(org.wso2.carbon.apimgt.impl.notifier.ExternallyDeployedApiNotifier) ApplicationRegistrationNotifier(org.wso2.carbon.apimgt.impl.notifier.ApplicationRegistrationNotifier) ApisNotifier(org.wso2.carbon.apimgt.impl.notifier.ApisNotifier) JWTValidationServiceImpl(org.wso2.carbon.apimgt.impl.jwt.JWTValidationServiceImpl) SystemScopesIssuer(org.wso2.carbon.apimgt.impl.issuers.SystemScopesIssuer) GoogleAnalyticsNotifier(org.wso2.carbon.apimgt.impl.notifier.GoogleAnalyticsNotifier) APIMConfigServiceImpl(org.wso2.carbon.apimgt.impl.config.APIMConfigServiceImpl) PolicyNotifier(org.wso2.carbon.apimgt.impl.notifier.PolicyNotifier) KeyStoreException(java.security.KeyStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OutputEventAdapterException(org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIManagerDatabaseException(org.wso2.carbon.apimgt.api.APIManagerDatabaseException) CertificateException(java.security.cert.CertificateException) ArtifactRetriever(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.ArtifactRetriever) CommonConfigDeployer(org.wso2.carbon.apimgt.impl.observers.CommonConfigDeployer) DeployAPIInGatewayNotifier(org.wso2.carbon.apimgt.impl.notifier.DeployAPIInGatewayNotifier) APIManagerAnalyticsConfiguration(org.wso2.carbon.apimgt.impl.APIManagerAnalyticsConfiguration) APIManagerConfigurationServiceImpl(org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl) Axis2ConfigurationContextObserver(org.wso2.carbon.utils.Axis2ConfigurationContextObserver) UserPostSelfRegistrationHandler(org.wso2.carbon.apimgt.impl.handlers.UserPostSelfRegistrationHandler) ScopesNotifier(org.wso2.carbon.apimgt.impl.notifier.ScopesNotifier) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) BundleContext(org.osgi.framework.BundleContext) TenantLoadMessageSender(org.wso2.carbon.apimgt.impl.observers.TenantLoadMessageSender) Cache(javax.cache.Cache) Activate(org.osgi.service.component.annotations.Activate)

Example 2 with JWTValidationService

use of org.wso2.carbon.apimgt.impl.jwt.JWTValidationService in project carbon-apimgt by wso2.

the class JWTValidatorTest method testJWTValidator.

@Test
public void testJWTValidator() throws ParseException, APISecurityException, APIManagementException, IOException {
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super");
    SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w");
    ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus");
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)).thenReturn("true");
    jwtValidator.setApiManagerConfiguration(apiManagerConfiguration);
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())).thenReturn(true);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Mockito.verify(apiKeyValidator).validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super");
    Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo);
    authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID());
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) SignedJWT(com.nimbusds.jwt.SignedJWT) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) ExtendedJWTConfigurationDto(org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with JWTValidationService

use of org.wso2.carbon.apimgt.impl.jwt.JWTValidationService in project carbon-apimgt by wso2.

the class JWTValidatorTest method testJWTValidatorForNonJTIScenario.

@Test
public void testJWTValidatorForNonJTIScenario() throws ParseException, APISecurityException, APIManagementException, IOException {
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super");
    SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJpc3MiOiJodHRwczovL2xvY2FsaG9zdCIsImlhdCI6MTU5OTU0ODE3NCwiZXhwIjoxNjMxMDg0MTc0LC" + "JhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiR2l2ZW5OYW1l" + "IjoiSm9obm55IiwiU3VybmFtZSI6IlJvY2tldCIsIkVtYWlsIjoianJvY2tldEBleGFtcGxlLmNvbSIsIl" + "JvbGUiOlsiTWFuYWdlciIsIlByb2plY3QgQWRtaW5pc3RyYXRvciJdfQ.SSQyg_VTxF5drIogztn2SyEK" + "2wRE07wG6OW3tufD3vo");
    ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus");
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)).thenReturn("true");
    jwtValidator.setApiManagerConfiguration(apiManagerConfiguration);
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())).thenReturn(true);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Mockito.verify(apiKeyValidator).validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.when(gatewayTokenCache.get(signedJWT.getSignature().toString())).thenReturn("carbon.super");
    Mockito.when(gatewayKeyCache.get(signedJWT.getSignature().toString())).thenReturn(jwtValidationInfo);
    authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getSignature().toString());
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) SignedJWT(com.nimbusds.jwt.SignedJWT) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) ExtendedJWTConfigurationDto(org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with JWTValidationService

use of org.wso2.carbon.apimgt.impl.jwt.JWTValidationService in project carbon-apimgt by wso2.

the class JWTValidatorTest method testJWTValidatorExpiredInCache.

@Test
public void testJWTValidatorExpiredInCache() throws ParseException, APISecurityException, APIManagementException, IOException {
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super");
    SignedJWT signedJWT = SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" + "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" + ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" + "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" + "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" + "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" + "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" + "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" + "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" + ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" + "CEFVQS1U3oY9" + "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" + "UMTwZ8" + "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" + "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" + "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" + "EuSe9w");
    ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus");
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION)).thenReturn("true");
    jwtValidator.setApiManagerConfiguration(apiManagerConfiguration);
    OpenAPIParser parser = new OpenAPIParser();
    String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json"));
    OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    Mockito.when(apiKeyValidator.validateScopes(Mockito.any(TokenValidationContext.class), Mockito.anyString())).thenReturn(true);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    Mockito.verify(apiKeyValidator).validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.when(gatewayTokenCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn("carbon.super");
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis() - 100);
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis());
    Mockito.when(gatewayKeyCache.get(signedJWT.getJWTClaimsSet().getJWTID())).thenReturn(jwtValidationInfo);
    try {
        authenticate = jwtValidator.authenticate(signedJWTInfo, messageContext);
    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    }
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWTInfo);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(1)).get(signedJWT.getJWTClaimsSet().getJWTID());
    Mockito.verify(invalidTokenCache, Mockito.times(1)).put(signedJWT.getJWTClaimsSet().getJWTID(), "carbon.super");
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) OpenAPIParser(io.swagger.parser.OpenAPIParser) SignedJWT(com.nimbusds.jwt.SignedJWT) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) ExtendedJWTConfigurationDto(org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) OpenAPI(io.swagger.v3.oas.models.OpenAPI) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with JWTValidationService

use of org.wso2.carbon.apimgt.impl.jwt.JWTValidationService in project carbon-apimgt by wso2.

the class JWTValidatorTest method testAuthenticateForGraphQLSubscription.

@Test
public void testAuthenticateForGraphQLSubscription() throws Exception {
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("carbon.super");
    SignedJWT signedJWT = SignedJWT.parse("eyJ4NXQiOiJNell4TW1Ga09HWXdNV0kwWldObU5EY3hOR1l3WW1NNFp" + "UQTNNV0kyTkRBelpHUXpOR00wWkdSbE5qSmtPREZrWkRSaU9URmtNV0ZoTXpVMlpHVmxOZyIsImtpZCI6Ik16WXhNbUZrT0" + "dZd01XSTBaV05tTkRjeE5HWXdZbU00WlRBM01XSTJOREF6WkdRek5HTTBaR1JsTmpKa09ERmtaRFJpT1RGa01XRmhNelUyW" + "kdWbE5nX1JTMjU2IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1dCI6IkFQUExJQ0FUSU9OIiwiYXVkIjoidT" + "ljaTNDRmRRUDZJNG9DNU84VFcwZklBRXRnYSIsIm5iZiI6MTYzNjkxNTk4OCwiYXpwIjoidTljaTNDRmRRUDZJNG9DNU84VFc" + "wZklBRXRnYSIsInNjb3BlIjoic2NvcGUxIiwiaXNzIjoiaHR0cHM6XC9cL2xvY2FsaG9zdDo5NDQzXC9vYXV0aDJcL3Rva2Vu" + "IiwiZXhwIjoxNjM2OTE5NTg4LCJpYXQiOjE2MzY5MTU5ODgsImp0aSI6IjJiM2FmYTkxLTBjNDItNGUzNC1iYTliLTc3ZmVkND" + "dkMGNmZCJ9.J8VkCSDUMCUNdJrpbRJy_cj5YazIrdRyNKTJ-9Lv1EabUgwENX1XQcUioSqF686ESI_PvUxYZIwViybVIIGVRuxM" + "Tp9vCMQDWhxXPCuehahul7Ebn0mQtrM7K2fwL0DpyKpI0ER_UYH-PgNvnHS0f3zmJdUBNao2QwuWorXMuwzSw3oPcdHcYmF9" + "Jn024J8Dv3ipHtzEgSc26ULVRaO9bDzJZochzQzqdkxjLMDMBYmKizXOCXEcXJYrEnQpTRHQGOuRN9stXePvO9_gFGVTenun" + "9pBT7Yw7D3Sd-qg-r_AnExOjQu8QwZRjTh_l09YwBYIrMdhSbtXpeAy0GNrc0w");
    SignedJWTInfo signedJWTInfo = new SignedJWTInfo(signedJWT.getParsedString(), signedJWT, signedJWT.getJWTClaimsSet());
    String apiContext = "/graphql";
    String apiVersion = "1.0.0";
    ExtendedJWTConfigurationDto jwtConfigurationDto = new ExtendedJWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5000L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Resident Key Manager");
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("GraphQLAPI");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    apiKeyValidationInfoDTO.setGraphQLMaxDepth(3);
    apiKeyValidationInfoDTO.setGraphQLMaxComplexity(4);
    // testing happy path
    Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto, jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticateForGraphQLSubscription(signedJWTInfo, apiContext, apiVersion);
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "GraphQLAPI");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Assert.assertEquals(authenticate.getRequestTokenScopes(), jwtValidationInfo.getScopes());
    Assert.assertEquals(authenticate.getGraphQLMaxComplexity(), apiKeyValidationInfoDTO.getGraphQLMaxComplexity());
    Assert.assertEquals(authenticate.getGraphQLMaxDepth(), apiKeyValidationInfoDTO.getGraphQLMaxDepth());
    // testing token validation failure
    jwtValidationInfo.setValid(false);
    Mockito.when(jwtValidationService.validateJWTToken(signedJWTInfo)).thenReturn(jwtValidationInfo);
    APISecurityException apiSecurityException = null;
    try {
        jwtValidator.authenticateForGraphQLSubscription(signedJWTInfo, apiContext, apiVersion);
    } catch (APISecurityException exception) {
        apiSecurityException = exception;
        Assert.assertEquals(exception.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
        Assert.assertEquals(exception.getMessage(), "Invalid JWT token");
    }
    if (apiSecurityException == null) {
        Assert.fail();
    }
    // testing subscription validation failure
    jwtValidationInfo.setValid(true);
    apiKeyValidationInfoDTO.setAuthorized(false);
    apiKeyValidationInfoDTO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN);
    try {
        jwtValidator.authenticateForGraphQLSubscription(signedJWTInfo, apiContext, apiVersion);
    } catch (APISecurityException exception) {
        Assert.assertEquals(exception.getErrorCode(), apiKeyValidationInfoDTO.getValidationStatus());
        Assert.assertEquals(exception.getMessage(), "User is NOT authorized to access the Resource. API Subscription validation failed.");
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) ExtendedJWTConfigurationDto(org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) JWTValidationService(org.wso2.carbon.apimgt.impl.jwt.JWTValidationService) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) SignedJWT(com.nimbusds.jwt.SignedJWT) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Cache (javax.cache.Cache)11 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)11 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)10 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)10 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)10 SignedJWT (com.nimbusds.jwt.SignedJWT)9 Test (org.junit.Test)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)9 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)9 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)9 HashMap (java.util.HashMap)8 MessageContext (org.apache.synapse.MessageContext)8 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)8 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)8 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)8 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)7 OpenAPIParser (io.swagger.parser.OpenAPIParser)3 OpenAPI (io.swagger.v3.oas.models.OpenAPI)3 IOException (java.io.IOException)1