Search in sources :

Example 41 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class RegistrationServiceImpl method register.

@POST
@Override
public Response register(RegistrationProfile profile) {
    /**
     * sample message to this method
     * {
     * "callbackUrl": "www.google.lk",
     * "clientName": "mdm",
     * "tokenScope": "Production",
     * "owner": "admin",
     * "grantType": "password refresh_token",
     * "saasApp": true
     *}
     */
    Response response;
    String applicationName = null;
    ErrorDTO errorDTO;
    try {
        OAuthAppRequest appRequest = new OAuthAppRequest();
        OAuthApplicationInfo oauthApplicationInfo = new OAuthApplicationInfo();
        OAuthApplicationInfo returnedAPP;
        String loggedInUserTenantDomain;
        String owner = profile.getOwner();
        String authUserName = RestApiCommonUtil.getLoggedInUsername();
        // correct domain
        if (owner != null && authUserName != null) {
            int index = authUserName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
            int ownerIndex = owner.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
            if (index > 0 && ownerIndex < 0) {
                if (!UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(authUserName.substring(0, index)) && owner.equals(authUserName.substring(index + 1))) {
                    if (log.isDebugEnabled()) {
                        log.debug("Update profile user name :" + owner + " with " + authUserName);
                    }
                    owner = authUserName;
                    profile.setOwner(owner);
                }
            }
        }
        // Validates if the application owner and logged in username is same.
        if (authUserName != null && ((authUserName.equals(owner)) || isUserSuperAdmin(authUserName))) {
            if (!isUserAccessAllowed(authUserName)) {
                String errorMsg = "You do not have enough privileges to create an OAuth app";
                log.error("User " + authUserName + " does not have any of subscribe/create/publish privileges " + "to create an OAuth app");
                errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403L, errorMsg);
                response = Response.status(Response.Status.FORBIDDEN).entity(errorDTO).build();
                return response;
            }
            // Getting client credentials from the profile
            String grantTypes = profile.getGrantType();
            oauthApplicationInfo.setClientName(profile.getClientName());
            if (StringUtils.isNotBlank(profile.getCallbackUrl())) {
                oauthApplicationInfo.setCallBackURL(profile.getCallbackUrl());
            } else {
                String[] grantTypeArr = grantTypes.split(" ");
                for (String grantType : grantTypeArr) {
                    if ((grantType.equalsIgnoreCase(ApplicationConstants.AUTHORIZATION_CODE)) || (grantType.equalsIgnoreCase(ApplicationConstants.IMPLICIT_CONST))) {
                        grantTypes = grantTypes.replace(grantType, "");
                    }
                }
            }
            String tokenType = APIConstants.DEFAULT_TOKEN_TYPE;
            String profileTokenType = profile.getTokenType();
            if (StringUtils.isNotEmpty(profileTokenType)) {
                tokenType = profileTokenType;
            }
            oauthApplicationInfo.addParameter(OAUTH_CLIENT_USERNAME, owner);
            oauthApplicationInfo.setClientId("");
            oauthApplicationInfo.setClientSecret("");
            oauthApplicationInfo.setIsSaasApplication(profile.isSaasApp());
            oauthApplicationInfo.setTokenType(tokenType);
            appRequest.setOAuthApplicationInfo(oauthApplicationInfo);
            if (!authUserName.equals(owner)) {
                loggedInUserTenantDomain = MultitenantUtils.getTenantDomain(owner);
            } else {
                loggedInUserTenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
            }
            String userId = (String) oauthApplicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
            String userNameForSP = MultitenantUtils.getTenantAwareUsername(userId);
            // Replace domain separator by "_" if user is coming from a secondary userstore.
            String domain = UserCoreUtil.extractDomainFromName(userNameForSP);
            if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
                userNameForSP = userNameForSP.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
            }
            applicationName = profile.getClientName();
            ApplicationManagementService applicationManagementService = ApplicationManagementService.getInstance();
            // Check if the application is already exists
            ServiceProvider appServiceProvider = null;
            try {
                appServiceProvider = applicationManagementService.getApplicationExcludingFileBasedSPs(applicationName, loggedInUserTenantDomain);
            } catch (IdentityApplicationManagementException e) {
                log.error("Error occurred while checking the existence of the application " + applicationName, e);
            }
            // Retrieving the existing application
            if (appServiceProvider != null) {
                returnedAPP = this.getExistingApp(applicationName, appServiceProvider.isSaasApp());
            } else {
                // create a new application if the application doesn't exists.
                returnedAPP = this.createApplication(applicationName, appRequest, grantTypes);
            }
            // ReturnedAPP is null
            if (returnedAPP == null) {
                String errorMsg = "OAuth app '" + profile.getClientName() + "' creation or updating failed." + " Dynamic Client Registration Service not available.";
                log.error(errorMsg);
                errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
                response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("OAuth app " + profile.getClientName() + " creation successful.");
                }
                response = Response.status(Response.Status.OK).entity(returnedAPP).build();
            }
        } else {
            String errorMsg = "Logged in user '" + authUserName + "' and application owner '" + owner + "' should be same.";
            errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg);
            response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMsg = "Error occurred while trying to create the client application " + applicationName;
        log.error(errorMsg, e);
        errorDTO = RestApiUtil.getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 500L, errorMsg);
        response = Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
    }
    return response;
}
Also used : FaultResponse(org.wso2.carbon.apimgt.rest.api.dcr.web.dto.FaultResponse) Response(javax.ws.rs.core.Response) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) POST(javax.ws.rs.POST)

Example 42 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class PublisherCommonUtils method encryptEndpointSecurityOAuthCredentials.

/**
 * This method will encrypt the OAuth 2.0 API Key and API Secret
 *
 * @param endpointConfig         endpoint configuration of API
 * @param cryptoUtil             cryptography util
 * @param oldProductionApiSecret existing production API secret
 * @param oldSandboxApiSecret    existing sandbox API secret
 * @param apidto                 API DTO
 * @throws CryptoException        if an error occurs while encrypting and base64 encode
 * @throws APIManagementException if an error occurs due to a problem in the endpointConfig payload
 */
public static void encryptEndpointSecurityOAuthCredentials(Map endpointConfig, CryptoUtil cryptoUtil, String oldProductionApiSecret, String oldSandboxApiSecret, APIDTO apidto) throws CryptoException, APIManagementException {
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    String customParametersString;
    if (endpointConfig != null) {
        if ((endpointConfig.get(APIConstants.ENDPOINT_SECURITY) != null)) {
            Map endpointSecurity = (Map) endpointConfig.get(APIConstants.ENDPOINT_SECURITY);
            if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION) != null) {
                Map endpointSecurityProduction = (Map) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                String productionEndpointType = (String) endpointSecurityProduction.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                // Change default value of customParameters JSONObject to String
                if (!(endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) instanceof String)) {
                    LinkedHashMap<String, String> customParametersHashMap = (LinkedHashMap<String, String>) endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                    customParametersString = JSONObject.toJSONString(customParametersHashMap);
                } else if (endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                    customParametersString = (String) endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                } else {
                    customParametersString = "{}";
                }
                endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParametersString);
                if (APIConstants.OAuthConstants.OAUTH.equals(productionEndpointType)) {
                    if (endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null && StringUtils.isNotBlank(endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString())) {
                        String apiSecret = endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                        String encryptedApiSecret = cryptoUtil.encryptAndBase64Encode(apiSecret.getBytes());
                        endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, encryptedApiSecret);
                    } else if (StringUtils.isNotBlank(oldProductionApiSecret)) {
                        endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, oldProductionApiSecret);
                    } else {
                        String errorMessage = "Client secret is not provided for production endpoint security";
                        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_ENDPOINT_CREDENTIALS, errorMessage));
                    }
                }
                endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityProduction);
                endpointConfig.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                apidto.setEndpointConfig(endpointConfig);
            }
            if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX) != null) {
                Map endpointSecuritySandbox = (Map) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                String sandboxEndpointType = (String) endpointSecuritySandbox.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                // Change default value of customParameters JSONObject to String
                if (!(endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) instanceof String)) {
                    Map<String, String> customParametersHashMap = (Map<String, String>) endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                    customParametersString = JSONObject.toJSONString(customParametersHashMap);
                } else if (endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                    customParametersString = (String) endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                } else {
                    customParametersString = "{}";
                }
                endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParametersString);
                if (APIConstants.OAuthConstants.OAUTH.equals(sandboxEndpointType)) {
                    if (endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null && StringUtils.isNotBlank(endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString())) {
                        String apiSecret = endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                        String encryptedApiSecret = cryptoUtil.encryptAndBase64Encode(apiSecret.getBytes());
                        endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, encryptedApiSecret);
                    } else if (StringUtils.isNotBlank(oldSandboxApiSecret)) {
                        endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, oldSandboxApiSecret);
                    } else {
                        String errorMessage = "Client secret is not provided for sandbox endpoint security";
                        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_ENDPOINT_CREDENTIALS, errorMessage));
                    }
                }
                endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecuritySandbox);
                endpointConfig.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                apidto.setEndpointConfig(endpointConfig);
            }
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 43 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class SecurityConfigContextTest method testSecurityConfigContextForAPIProductWithOAuth.

@Test
public void testSecurityConfigContextForAPIProductWithOAuth() throws Exception {
    APIProduct apiProduct = new APIProduct(new APIProductIdentifier("admin", "TestProduct", "1.0.0"));
    apiProduct.setUuid(UUID.randomUUID().toString());
    String apiid = UUID.randomUUID().toString();
    List<APIProductResource> apiProductResourceList = new ArrayList<>();
    APIProductResource apiProductResource = new APIProductResource();
    apiProductResource.setApiIdentifier(new APIIdentifier("admin_api1_v1"));
    apiProductResource.setApiId(apiid);
    Map<String, EndpointSecurity> endpointSecurityMap = new HashMap<>();
    EndpointSecurity endpointSecurity = new EndpointSecurity();
    endpointSecurity.setType("oauth");
    endpointSecurity.setClientId("123-456");
    endpointSecurity.setClientSecret("admin123");
    endpointSecurity.setGrantType("client_credentials");
    endpointSecurity.setEnabled(true);
    endpointSecurityMap.put("production", endpointSecurity);
    apiProductResource.setApiId(apiid);
    apiProductResource.setEndpointSecurityMap(endpointSecurityMap);
    apiProductResourceList.add(apiProductResource);
    apiProduct.setProductResources(apiProductResourceList);
    ConfigContext configcontext = new APIConfigContext(apiProduct);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    Map<String, APIDTO> apidtoMap = new HashMap<>();
    apidtoMap.put(apiid, new APIDTO().name("api1").version("v1").provider("admin").id(UUID.randomUUID().toString()));
    SecurityConfigContext securityConfigContext = new SecurityConfigContextWrapper(configcontext, apiProduct, apiManagerConfiguration, apidtoMap);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = (Map<String, Map<String, EndpointSecurityModel>>) velocityContext.get("endpoint_security");
    Map<String, EndpointSecurityModel> endpointSecurityModelMap1 = endpointSecurityModelMap.get(apiProductResource.getApiId());
    EndpointSecurityModel production = endpointSecurityModelMap1.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("oauth"));
    Assert.assertTrue("Property username does not match.", "123-456".equals(production.getClientId()));
    Assert.assertEquals(production.getClientSecretAlias(), "TestProduct--v1.0.0--api1--vv1--oauth--clientSecret" + "--production");
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ", velocityContext.get("isSecureVaultEnabled").equals(true));
}
Also used : SecurityConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.SecurityConfigContext) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) ArrayList(java.util.ArrayList) EndpointSecurity(org.wso2.carbon.apimgt.api.model.EndpointSecurity) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) EndpointSecurityModel(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.EndpointSecurityModel) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) HashMap(java.util.HashMap) Map(java.util.Map) APIConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APIConfigContext) ConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.ConfigContext) SecurityConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.SecurityConfigContext) APIConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APIConfigContext) Test(org.junit.Test)

Example 44 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method publishSessionTermination.

/**
 * Overridden method which implements the access token revocation
 * @param request termination request
 * @param context termination context
 * @param sessionContext termination sessionContext
 * @param params termination params
 */
@Override
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    OAuthConsumerAppDTO[] appDTOs = new OAuthConsumerAppDTO[0];
    List<OAuthConsumerAppDTO> revokeAppList = new ArrayList<>();
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) params.get(user);
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    AuthenticatedUser federatedUser;
    SystemApplicationDTO[] systemApplicationDTOS = new SystemApplicationDTO[0];
    if (authenticatedUser.isFederatedUser()) {
        try {
            federatedUser = buildAuthenticatedUser(authenticatedUser);
            authenticatedUser = federatedUser;
        } catch (IdentityOAuth2Exception e) {
            log.error("Error thrown while building authenticated user in logout flow for user " + authenticatedUser.getUserName(), e);
        }
    }
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    try {
        appDTOs = getAppsAuthorizedByUser(authenticatedUser);
        if (appDTOs.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("The user: " + authenticatedUser.getUserName() + " has " + appDTOs.length + " OAuth apps");
            }
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error while retrieving applications authorized for the user " + authenticatedUser.getUserName(), e);
    }
    for (OAuthConsumerAppDTO appDTO : appDTOs) {
        for (SystemApplicationDTO systemApplicationDTO : systemApplicationDTOS) {
            if (StringUtils.equalsIgnoreCase(appDTO.getOauthConsumerKey(), systemApplicationDTO.getConsumerKey())) {
                revokeAppList.add(appDTO);
            }
        }
    }
    for (OAuthConsumerAppDTO appDTO : revokeAppList) {
        Set<AccessTokenDO> accessTokenDOs = null;
        try {
            // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this user
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), authenticatedUser, authenticatedUser.getUserStoreDomain(), true);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error while retrieving access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
        }
        AuthenticatedUser authzUser;
        if (accessTokenDOs != null) {
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                // Clear cache with AccessTokenDO
                authzUser = accessTokenDO.getAuthzUser();
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()), "NONE");
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
                Cache restApiTokenCache = CacheProvider.getRESTAPITokenCache();
                if (restApiTokenCache != null) {
                    restApiTokenCache.remove(accessTokenDO.getAccessToken());
                }
                AccessTokenDO scopedToken = null;
                try {
                    // Retrieve latest access token for particular client, user and scope combination if
                    // its ACTIVE or EXPIRED.
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), authenticatedUser, userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
                } catch (IdentityOAuth2Exception e) {
                    log.error("Error while retrieving scoped access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                }
                if (scopedToken != null) {
                    // Revoking token from database
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                    // Revoking the oauth consent from database.
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, username);
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                }
            }
        }
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) Cache(javax.cache.Cache)

Example 45 with OAuth

use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.

the class PublisherCommonUtils method updateApi.

/**
 * Update an API.
 *
 * @param originalAPI    Existing API
 * @param apiDtoToUpdate New API DTO to update
 * @param apiProvider    API Provider
 * @param tokenScopes    Scopes of the token
 * @throws ParseException         If an error occurs while parsing the endpoint configuration
 * @throws CryptoException        If an error occurs while encrypting the secret key of API
 * @throws APIManagementException If an error occurs while updating the API
 * @throws FaultGatewaysException If an error occurs while updating manage of an existing API
 */
public static API updateApi(API originalAPI, APIDTO apiDtoToUpdate, APIProvider apiProvider, String[] tokenScopes) throws ParseException, CryptoException, APIManagementException, FaultGatewaysException {
    APIIdentifier apiIdentifier = originalAPI.getId();
    // Validate if the USER_REST_API_SCOPES is not set in WebAppAuthenticator when scopes are validated
    if (tokenScopes == null) {
        throw new APIManagementException("Error occurred while updating the  API " + originalAPI.getUUID() + " as the token information hasn't been correctly set internally", ExceptionCodes.TOKEN_SCOPES_NOT_SET);
    }
    boolean isGraphql = originalAPI.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(originalAPI.getType());
    boolean isAsyncAPI = originalAPI.getType() != null && (APIConstants.APITransportType.WS.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.WEBSUB.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.SSE.toString().equals(originalAPI.getType()) || APIConstants.APITransportType.ASYNC.toString().equals(originalAPI.getType()));
    Scope[] apiDtoClassAnnotatedScopes = APIDTO.class.getAnnotationsByType(Scope.class);
    boolean hasClassLevelScope = checkClassScopeAnnotation(apiDtoClassAnnotatedScopes, tokenScopes);
    JSONParser parser = new JSONParser();
    String oldEndpointConfigString = originalAPI.getEndpointConfig();
    JSONObject oldEndpointConfig = null;
    if (StringUtils.isNotBlank(oldEndpointConfigString)) {
        oldEndpointConfig = (JSONObject) parser.parse(oldEndpointConfigString);
    }
    String oldProductionApiSecret = null;
    String oldSandboxApiSecret = null;
    if (oldEndpointConfig != null) {
        if ((oldEndpointConfig.containsKey(APIConstants.ENDPOINT_SECURITY))) {
            JSONObject oldEndpointSecurity = (JSONObject) oldEndpointConfig.get(APIConstants.ENDPOINT_SECURITY);
            if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION)) {
                JSONObject oldEndpointSecurityProduction = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                if (oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
                    oldProductionApiSecret = oldEndpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                }
            }
            if (oldEndpointSecurity.containsKey(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX)) {
                JSONObject oldEndpointSecuritySandbox = (JSONObject) oldEndpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                if (oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_ID) != null && oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null) {
                    oldSandboxApiSecret = oldEndpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                }
            }
        }
    }
    Map endpointConfig = (Map) apiDtoToUpdate.getEndpointConfig();
    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, oldProductionApiSecret, oldSandboxApiSecret, apiDtoToUpdate);
    // AWS Lambda: secret key encryption while updating the API
    if (apiDtoToUpdate.getEndpointConfig() != null) {
        if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
            String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            if (!StringUtils.isEmpty(secretKey)) {
                if (!APIConstants.AWS_SECRET_KEY.equals(secretKey)) {
                    String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
                    endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                    apiDtoToUpdate.setEndpointConfig(endpointConfig);
                } else {
                    JSONParser jsonParser = new JSONParser();
                    JSONObject originalEndpointConfig = (JSONObject) jsonParser.parse(originalAPI.getEndpointConfig());
                    String encryptedSecretKey = (String) originalEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
                    endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                    apiDtoToUpdate.setEndpointConfig(endpointConfig);
                }
            }
        }
    }
    if (!hasClassLevelScope) {
        // Validate per-field scopes
        apiDtoToUpdate = getFieldOverriddenAPIDTO(apiDtoToUpdate, originalAPI, tokenScopes);
    }
    // API Name change not allowed if OnPrem
    if (APIUtil.isOnPremResolver()) {
        apiDtoToUpdate.setName(apiIdentifier.getApiName());
    }
    apiDtoToUpdate.setVersion(apiIdentifier.getVersion());
    apiDtoToUpdate.setProvider(apiIdentifier.getProviderName());
    apiDtoToUpdate.setContext(originalAPI.getContextTemplate());
    apiDtoToUpdate.setLifeCycleStatus(originalAPI.getStatus());
    apiDtoToUpdate.setType(APIDTO.TypeEnum.fromValue(originalAPI.getType()));
    List<APIResource> removedProductResources = getRemovedProductResources(apiDtoToUpdate, originalAPI);
    if (!removedProductResources.isEmpty()) {
        throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, originalAPI.getId().getApiName(), originalAPI.getId().getVersion()));
    }
    // Validate API Security
    List<String> apiSecurity = apiDtoToUpdate.getSecurityScheme();
    // validation for tiers
    List<String> tiersFromDTO = apiDtoToUpdate.getPolicies();
    String originalStatus = originalAPI.getStatus();
    if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
        if ((tiersFromDTO == null || tiersFromDTO.isEmpty() && !(APIConstants.CREATED.equals(originalStatus) || APIConstants.PROTOTYPED.equals(originalStatus))) && !apiDtoToUpdate.getAdvertiseInfo().isAdvertised()) {
            throw new APIManagementException("A tier should be defined if the API is not in CREATED or PROTOTYPED state", ExceptionCodes.TIER_CANNOT_BE_NULL);
        }
    }
    if (tiersFromDTO != null && !tiersFromDTO.isEmpty()) {
        // check whether the added API's tiers are all valid
        Set<Tier> definedTiers = apiProvider.getTiers();
        List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
        if (invalidTiers.size() > 0) {
            throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
        }
    }
    if (apiDtoToUpdate.getAccessControlRoles() != null) {
        String errorMessage = validateUserRoles(apiDtoToUpdate.getAccessControlRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (apiDtoToUpdate.getVisibleRoles() != null) {
        String errorMessage = validateRoles(apiDtoToUpdate.getVisibleRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (apiDtoToUpdate.getAdditionalProperties() != null) {
        String errorMessage = validateAdditionalProperties(apiDtoToUpdate.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiDtoToUpdate.getName(), apiDtoToUpdate.getVersion()));
        }
    }
    // Validate if resources are empty
    if (apiDtoToUpdate.getOperations() == null || apiDtoToUpdate.getOperations().isEmpty()) {
        throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
    }
    API apiToUpdate = APIMappingUtil.fromDTOtoAPI(apiDtoToUpdate, apiIdentifier.getProviderName());
    if (APIConstants.PUBLIC_STORE_VISIBILITY.equals(apiToUpdate.getVisibility())) {
        apiToUpdate.setVisibleRoles(StringUtils.EMPTY);
    }
    apiToUpdate.setUUID(originalAPI.getUUID());
    apiToUpdate.setOrganization(originalAPI.getOrganization());
    validateScopes(apiToUpdate);
    apiToUpdate.setThumbnailUrl(originalAPI.getThumbnailUrl());
    if (apiDtoToUpdate.getKeyManagers() instanceof List) {
        apiToUpdate.setKeyManagers((List<String>) apiDtoToUpdate.getKeyManagers());
    } else {
        apiToUpdate.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    }
    if (!isAsyncAPI) {
        String oldDefinition = apiProvider.getOpenAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
        APIDefinition apiDefinition = OASParserUtil.getOASParser(oldDefinition);
        SwaggerData swaggerData = new SwaggerData(apiToUpdate);
        String newDefinition = apiDefinition.generateAPIDefinition(swaggerData, oldDefinition);
        apiProvider.saveSwaggerDefinition(apiToUpdate, newDefinition, originalAPI.getOrganization());
        if (!isGraphql) {
            Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(newDefinition);
            // set operation policies from the original API Payload
            Set<URITemplate> uriTemplatesFromPayload = apiToUpdate.getUriTemplates();
            Map<String, List<OperationPolicy>> operationPoliciesPerURITemplate = new HashMap<>();
            for (URITemplate uriTemplate : uriTemplatesFromPayload) {
                if (!uriTemplate.getOperationPolicies().isEmpty()) {
                    String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
                    operationPoliciesPerURITemplate.put(key, uriTemplate.getOperationPolicies());
                }
            }
            for (URITemplate uriTemplate : uriTemplates) {
                String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
                if (operationPoliciesPerURITemplate.containsKey(key)) {
                    uriTemplate.setOperationPolicies(operationPoliciesPerURITemplate.get(key));
                }
            }
            apiToUpdate.setUriTemplates(uriTemplates);
        }
    } else {
        String oldDefinition = apiProvider.getAsyncAPIDefinition(apiToUpdate.getUuid(), originalAPI.getOrganization());
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String updateAsyncAPIDefinition = asyncApiParser.updateAsyncAPIDefinition(oldDefinition, apiToUpdate);
        apiProvider.saveAsyncApiDefinition(originalAPI, updateAsyncAPIDefinition);
    }
    apiToUpdate.setWsdlUrl(apiDtoToUpdate.getWsdlUrl());
    // validate API categories
    List<APICategory> apiCategories = apiToUpdate.getApiCategories();
    List<APICategory> apiCategoriesList = new ArrayList<>();
    for (APICategory category : apiCategories) {
        category.setOrganization(originalAPI.getOrganization());
        apiCategoriesList.add(category);
    }
    apiToUpdate.setApiCategories(apiCategoriesList);
    if (apiCategoriesList.size() > 0) {
        if (!APIUtil.validateAPICategories(apiCategoriesList, originalAPI.getOrganization())) {
            throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
        }
    }
    apiToUpdate.setOrganization(originalAPI.getOrganization());
    apiProvider.updateAPI(apiToUpdate, originalAPI);
    return apiProvider.getAPIbyUUID(originalAPI.getUuid(), originalAPI.getOrganization());
// TODO use returend api
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ArrayList(java.util.ArrayList) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) List(java.util.List) ArrayList(java.util.ArrayList) Tier(org.wso2.carbon.apimgt.api.model.Tier) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) JSONObject(org.json.simple.JSONObject) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) JSONParser(org.json.simple.parser.JSONParser) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5