Search in sources :

Example 1 with APIKeyMgtException

use of org.wso2.carbon.apimgt.keymgt.APIKeyMgtException in project carbon-apimgt by wso2.

the class RegistrationServiceImpl method createApplication.

/**
 * Create a new client application
 *
 * @param appRequest OAuthAppRequest object with client's payload content
 * @return created Application
 * @throws APIKeyMgtException if failed to create the a new application
 */
private OAuthApplicationInfo createApplication(String applicationName, OAuthAppRequest appRequest, String grantType) throws APIManagementException {
    String userName;
    OAuthApplicationInfo applicationInfo = appRequest.getOAuthApplicationInfo();
    String appName = applicationInfo.getClientName();
    String userId = (String) applicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
    boolean isTenantFlowStarted = false;
    if (userId == null || userId.isEmpty()) {
        return null;
    }
    userName = MultitenantUtils.getTenantAwareUsername(userId);
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
        }
        // Creating the service provider
        ServiceProvider serviceProvider = new ServiceProvider();
        serviceProvider.setApplicationName(applicationName);
        serviceProvider.setDescription("Service Provider for application " + appName);
        serviceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        ServiceProviderProperty[] serviceProviderProperties = new ServiceProviderProperty[4];
        ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
        serviceProviderProperty.setName(APP_DISPLAY_NAME);
        serviceProviderProperty.setValue(applicationName);
        serviceProviderProperties[0] = serviceProviderProperty;
        ServiceProviderProperty tokenTypeProviderProperty = new ServiceProviderProperty();
        tokenTypeProviderProperty.setName(APIConstants.APP_TOKEN_TYPE);
        tokenTypeProviderProperty.setValue(applicationInfo.getTokenType());
        serviceProviderProperties[1] = tokenTypeProviderProperty;
        ServiceProviderProperty consentProperty = new ServiceProviderProperty();
        consentProperty.setDisplayName(APIConstants.APP_SKIP_CONSENT_DISPLAY);
        consentProperty.setName(APIConstants.APP_SKIP_CONSENT_NAME);
        consentProperty.setValue(APIConstants.APP_SKIP_CONSENT_VALUE);
        serviceProviderProperties[2] = consentProperty;
        ServiceProviderProperty logoutConsentProperty = new ServiceProviderProperty();
        logoutConsentProperty.setDisplayName(APIConstants.APP_SKIP_LOGOUT_CONSENT_DISPLAY);
        logoutConsentProperty.setName(APIConstants.APP_SKIP_LOGOUT_CONSENT_NAME);
        logoutConsentProperty.setValue(APIConstants.APP_SKIP_LOGOUT_CONSENT_VALUE);
        serviceProviderProperties[3] = logoutConsentProperty;
        serviceProvider.setSpProperties(serviceProviderProperties);
        ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
        appMgtService.createApplication(serviceProvider, tenantDomain, userName);
        // Retrieving the created service provider
        ServiceProvider createdServiceProvider = appMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
        if (createdServiceProvider == null) {
            throw new APIManagementException("Error occurred while creating Service Provider " + "Application" + appName);
        }
        // creating the OAuth app
        OAuthConsumerAppDTO createdOauthApp = this.createOAuthApp(applicationName, applicationInfo, grantType, userName);
        // Set the OAuthApp in InboundAuthenticationConfig
        InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
        InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new InboundAuthenticationRequestConfig[1];
        InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
        String oAuthType = APIConstants.SWAGGER_12_OAUTH2;
        inboundAuthenticationRequestConfig.setInboundAuthType(oAuthType);
        inboundAuthenticationRequestConfig.setInboundAuthKey(createdOauthApp.getOauthConsumerKey());
        String oauthConsumerSecret = createdOauthApp.getOauthConsumerSecret();
        if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
            Property property = new Property();
            property.setName(ApplicationConstants.INBOUNT_AUTH_CONSUMER_SECRET);
            property.setValue(oauthConsumerSecret);
            Property[] properties = { property };
            inboundAuthenticationRequestConfig.setProperties(properties);
        }
        inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
        inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs);
        createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
        // Setting the SaasApplication attribute to created service provider
        createdServiceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        createdServiceProvider.setSpProperties(serviceProviderProperties);
        // Updating the service provider with Inbound Authentication Configs and SaasApplication
        appMgtService.updateApplication(createdServiceProvider, tenantDomain, userName);
        Map<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(OAUTH_REDIRECT_URIS, createdOauthApp.getCallbackUrl());
        valueMap.put(OAUTH_CLIENT_NAME, createdOauthApp.getApplicationName());
        valueMap.put(OAUTH_CLIENT_GRANT, createdOauthApp.getGrantTypes());
        return this.fromAppDTOToApplicationInfo(createdOauthApp.getOauthConsumerKey(), applicationName, createdOauthApp.getCallbackUrl(), createdOauthApp.getOauthConsumerSecret(), createdServiceProvider.isSaasApp(), userId, valueMap);
    } catch (IdentityApplicationManagementException e) {
        log.error("Error occurred while creating the client application " + appName, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
        }
    }
    return null;
}
Also used : InboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig) HashMap(java.util.HashMap) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) Property(org.wso2.carbon.identity.application.common.model.Property)

Example 2 with APIKeyMgtException

use of org.wso2.carbon.apimgt.keymgt.APIKeyMgtException in project carbon-apimgt by wso2.

the class APIKeyValidationService method validateKeyForHandshake.

/**
 * Validate access token for websocket handshake
 *
 * @param context          context of the API
 * @param version          version of the API
 * @param accessToken      access token of the request
 * @param tenantDomain
 * @param keyManagers
 * @return
 * @throws APIKeyMgtException
 * @throws APIManagementException
 */
public APIKeyValidationInfoDTO validateKeyForHandshake(String context, String version, String accessToken, String tenantDomain, List<String> keyManagers) throws APIKeyMgtException, APIManagementException {
    APIKeyValidationInfoDTO info = new APIKeyValidationInfoDTO();
    info.setAuthorized(false);
    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setAccessToken(accessToken);
    validationContext.setContext(context);
    validationContext.setValidationInfoDTO(new APIKeyValidationInfoDTO());
    validationContext.setVersion(version);
    validationContext.setTenantDomain(tenantDomain);
    validationContext.setRequiredAuthenticationLevel("Any");
    validationContext.setKeyManagers(keyManagers);
    KeyValidationHandler keyValidationHandler = ServiceReferenceHolder.getInstance().getKeyValidationHandler(tenantDomain);
    boolean state = keyValidationHandler.validateToken(validationContext);
    if (state) {
        state = keyValidationHandler.validateSubscription(validationContext);
        if (state) {
            if (APIKeyMgtDataHolder.isJwtGenerationEnabled() && validationContext.getValidationInfoDTO().getEndUserName() != null && !validationContext.isCacheHit()) {
                Application application = APIUtil.getApplicationByClientId(validationContext.getValidationInfoDTO().getConsumerKey());
                validationContext.getValidationInfoDTO().setApplicationId(String.valueOf(application.getId()));
                validationContext.getValidationInfoDTO().setApplicationTier(application.getTier());
                keyValidationHandler.generateConsumerToken(validationContext);
                info.setEndUserToken(validationContext.getValidationInfoDTO().getEndUserToken());
            }
        }
        return validationContext.getValidationInfoDTO();
    }
    return info;
}
Also used : KeyValidationHandler(org.wso2.carbon.apimgt.keymgt.handlers.KeyValidationHandler) Application(org.wso2.carbon.apimgt.api.model.Application) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 3 with APIKeyMgtException

use of org.wso2.carbon.apimgt.keymgt.APIKeyMgtException in project carbon-apimgt by wso2.

the class DefaultKeyValidationHandlerTest method testValidateScopes.

@Test
public void testValidateScopes() throws APIKeyMgtException {
    API api = new API();
    api.setApiId(1);
    api.setApiProvider(USER_NAME);
    api.setApiName(API_NAME);
    api.setApiVersion(API_VERSION);
    api.setContext(API_CONTEXT);
    URLMapping urlMapping = new URLMapping();
    urlMapping.addScope(SCOPES);
    urlMapping.setHttpMethod(HTTP_VERB);
    urlMapping.setUrlPattern(RESOURCE);
    api.addResource(urlMapping);
    Map<String, API> apiMap = new HashMap<>();
    String key = API_CONTEXT + ":" + API_VERSION;
    apiMap.put(key, api);
    APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
    dto.setSubscriber(SUBSCRIBER);
    dto.setApplicationName(APPLICATION_NAME);
    dto.setApplicationId(APPLICATION_ID);
    dto.setApplicationTier(TIER);
    Set<String> scopeSet = new HashSet<>();
    scopeSet.add(SCOPES);
    dto.setScopes(scopeSet);
    dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
    // TokenValidationContext for non default API
    TokenValidationContext param1 = new TokenValidationContext();
    param1.setValidationInfoDTO(dto);
    param1.setContext(API_CONTEXT);
    param1.setVersion(API_VERSION);
    param1.setAccessToken(ACCESS_TOKEN);
    param1.setMatchingResource(RESOURCE);
    param1.setHttpVerb(HTTP_VERB);
    // TokenValidationContext for default API version
    TokenValidationContext param2 = new TokenValidationContext();
    param2.setValidationInfoDTO(dto);
    param2.setContext(API_CONTEXT);
    param2.setVersion(DEFAULT_API_VERSION);
    param2.setAccessToken(ACCESS_TOKEN);
    param2.setMatchingResource(RESOURCE);
    param2.setHttpVerb(HTTP_VERB);
    Mockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
    Mockito.when(subscriptionDataHolder.getTenantSubscriptionStore(eq(TENANT_DOMAIN))).thenReturn(tenantSubscriptionStore);
    Mockito.when(tenantSubscriptionStore.getApiByContextAndVersion(eq(API_CONTEXT), eq(API_VERSION))).thenReturn(api);
    DefaultKeyValidationHandler defaultKeyValidationHandler = new DefaultKeyValidationHandler();
    boolean isScopeValidated = defaultKeyValidationHandler.validateScopes(param1);
    boolean isScopeValidated_default = defaultKeyValidationHandler.validateScopes(param2);
    Assert.assertTrue("Scope validation fails for API " + API_NAME, isScopeValidated);
    Assert.assertTrue("Scope validation fails for default API " + API_NAME, isScopeValidated_default);
}
Also used : URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) TokenValidationContext(org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext) HashMap(java.util.HashMap) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with APIKeyMgtException

use of org.wso2.carbon.apimgt.keymgt.APIKeyMgtException in project carbon-apimgt by wso2.

the class DefaultKeyValidationHandlerTest method testInvalidSubscription.

@Test
public void testInvalidSubscription() throws APIKeyMgtException {
    DefaultKeyValidationHandler defaultKeyValidationHandler = new DefaultKeyValidationHandler();
    API api = new API();
    api.setApiId(1);
    api.setApiProvider(USER_NAME);
    api.setApiName(API_NAME);
    api.setApiVersion(API_VERSION);
    api.setContext(API_CONTEXT);
    URLMapping urlMapping = new URLMapping();
    urlMapping.addScope(SCOPES);
    urlMapping.setHttpMethod(HTTP_VERB);
    urlMapping.setUrlPattern(RESOURCE);
    api.addResource(urlMapping);
    Mockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
    Mockito.when(subscriptionDataHolder.getTenantSubscriptionStore(eq(TENANT_DOMAIN))).thenReturn(tenantSubscriptionStore);
    Mockito.when(tenantSubscriptionStore.getApiByContextAndVersion(eq(API_CONTEXT), eq(API_VERSION))).thenReturn(api);
    APIKeyValidationInfoDTO info = defaultKeyValidationHandler.validateSubscription(API_CONTEXT, API_VERSION, "xxxxxx", "default");
    Assert.assertEquals("Invalid error message status code ", APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN, info.getValidationStatus());
}
Also used : URLMapping(org.wso2.carbon.apimgt.api.model.subscription.URLMapping) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 5 with APIKeyMgtException

use of org.wso2.carbon.apimgt.keymgt.APIKeyMgtException in project carbon-apimgt by wso2.

the class AbstractKeyValidationHandler method validateSubscription.

@Override
public boolean validateSubscription(TokenValidationContext validationContext) throws APIKeyMgtException {
    if (validationContext == null || validationContext.getValidationInfoDTO() == null) {
        return false;
    }
    if (validationContext.isCacheHit()) {
        return true;
    }
    APIKeyValidationInfoDTO dto = validationContext.getValidationInfoDTO();
    if (validationContext.getTokenInfo() != null) {
        if (validationContext.getTokenInfo().isApplicationToken()) {
            dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
        } else {
            dto.setUserType(APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN);
        }
        AccessTokenInfo tokenInfo = validationContext.getTokenInfo();
        // Application Token
        if (!hasTokenRequiredAuthLevel(validationContext.getRequiredAuthenticationLevel(), tokenInfo)) {
            dto.setAuthorized(false);
            dto.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INCORRECT_ACCESS_TOKEN_TYPE);
            return false;
        }
    }
    boolean state = false;
    try {
        if (log.isDebugEnabled()) {
            log.debug("Before validating subscriptions : " + dto);
            log.debug("Validation Info : { context : " + validationContext.getContext() + " , " + "version : " + validationContext.getVersion() + " , consumerKey : " + dto.getConsumerKey() + " }");
        }
        state = validateSubscriptionDetails(validationContext.getContext(), validationContext.getVersion(), dto.getConsumerKey(), dto.getKeyManager(), dto);
        if (log.isDebugEnabled()) {
            log.debug("After validating subscriptions : " + dto);
        }
    } catch (APIManagementException e) {
        log.error("Error Occurred while validating subscription.", e);
    }
    return state;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Aggregations

APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 HashMap (java.util.HashMap)3 URLMapping (org.wso2.carbon.apimgt.api.model.subscription.URLMapping)3 APIKeyMgtException (org.wso2.carbon.apimgt.keymgt.APIKeyMgtException)3 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)3 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)2 KeyValidationHandler (org.wso2.carbon.apimgt.keymgt.handlers.KeyValidationHandler)2 SimpleDateFormat (java.text.SimpleDateFormat)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 List (java.util.List)1 Map (java.util.Map)1 Cache (javax.cache.Cache)1 AxisFault (org.apache.axis2.AxisFault)1 MessageContext (org.apache.axis2.context.MessageContext)1 Header (org.apache.commons.httpclient.Header)1