Search in sources :

Example 1 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project carbon-identity-framework by wso2.

the class IdentityManagementEndpointUtil method getBasePath.

/**
 * Get base path URL for API clients.
 *
 * @param tenantDomain          Tenant Domain.
 * @param context               URL context.
 * @param isEndpointTenantAware Whether the endpoint is tenant aware.
 * @return Base path.
 * @throws ApiException ApiException.
 */
public static String getBasePath(String tenantDomain, String context, boolean isEndpointTenantAware) throws ApiException {
    String basePath;
    String serverUrl = IdentityManagementServiceUtil.getInstance().getContextURLFromFile();
    try {
        if (StringUtils.isBlank(serverUrl)) {
            if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
                basePath = ServiceURLBuilder.create().addPath(context).setTenant(tenantDomain).build().getAbsoluteInternalURL();
            } else {
                serverUrl = ServiceURLBuilder.create().build().getAbsoluteInternalURL();
                if (StringUtils.isNotBlank(tenantDomain) && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain) && isEndpointTenantAware) {
                    basePath = serverUrl + "/t/" + tenantDomain + context;
                } else {
                    basePath = serverUrl + context;
                }
            }
        } else {
            if (StringUtils.isNotBlank(tenantDomain) && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain) && isEndpointTenantAware) {
                basePath = serverUrl + "/t/" + tenantDomain + context;
            } else {
                basePath = serverUrl + context;
            }
        }
    } catch (URLBuilderException e) {
        throw new ApiException("Error while building url for context: " + context);
    }
    return basePath;
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) ApiException(org.wso2.carbon.identity.mgt.endpoint.util.client.ApiException)

Example 2 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project carbon-identity-framework by wso2.

the class IdentityManagementServiceUtil method init.

/**
 * Loads the properties defined in RecoveryEndpointConfig.properties file
 */
public void init() {
    InputStream inputStream = null;
    jsonProvider.setDropRootElement(true);
    jsonProvider.setIgnoreNamespaces(true);
    jsonProvider.setValidateOutput(true);
    jsonProvider.setSupportUnwrapped(true);
    providers.add(jsonProvider);
    try {
        Properties properties = new Properties();
        File currentDirectory = new File(new File(IdentityManagementEndpointConstants.RELATIVE_PATH_START_CHAR).getAbsolutePath());
        String configFilePath = currentDirectory.getCanonicalPath() + File.separator + IdentityManagementEndpointConstants.SERVICE_CONFIG_RELATIVE_PATH;
        File configFile = new File(configFilePath);
        if (configFile.exists()) {
            if (log.isDebugEnabled()) {
                log.debug(IdentityManagementEndpointConstants.SERVICE_CONFIG_FILE_NAME + " file loaded from " + IdentityManagementEndpointConstants.SERVICE_CONFIG_RELATIVE_PATH);
            }
            inputStream = new FileInputStream(configFile);
            properties.load(inputStream);
            resolveSecrets(properties);
        } else {
            if (log.isDebugEnabled()) {
                log.debug(IdentityManagementEndpointConstants.SERVICE_CONFIG_FILE_NAME + " file loaded from account recovery endpoint webapp");
            }
            inputStream = IdentityManagementServiceUtil.class.getClassLoader().getResourceAsStream(IdentityManagementEndpointConstants.SERVICE_CONFIG_FILE_NAME);
            properties.load(inputStream);
        }
        accessUsername = properties.getProperty(IdentityManagementEndpointConstants.ServiceConfigConstants.SERVICE_ACCESS_USERNAME);
        accessPassword = properties.getProperty(IdentityManagementEndpointConstants.ServiceConfigConstants.SERVICE_ACCESS_PASSWORD);
        appName = properties.getProperty(IdentityManagementEndpointConstants.ServiceConfigConstants.APP_NAME);
        appPassword = properties.getProperty(IdentityManagementEndpointConstants.ServiceConfigConstants.APP_PASSWORD).toCharArray();
        String serviceContextURL = properties.getProperty(IdentityManagementEndpointConstants.ServiceConfigConstants.SERVICE_CONTEXT_URL);
        contextURL = serviceContextURL;
        this.serviceContextURL = StringUtils.isBlank(serviceContextURL) ? ServiceURLBuilder.create().addPath(IdentityUtil.getServicePath()).build().getAbsoluteInternalURL() : serviceContextURL;
    } catch (IOException e) {
        log.error("Failed to load service configurations.", e);
    } catch (URLBuilderException e) {
        log.error("Error occurred while building service URL.", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Failed to close the FileInputStream for file : " + IdentityManagementEndpointConstants.SERVICE_CONFIG_FILE_NAME, e);
            }
        }
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) HttpTransportProperties(org.apache.axis2.transport.http.HttpTransportProperties) Properties(java.util.Properties) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 3 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project carbon-identity-framework by wso2.

the class DefaultServiceURLBuilderTest method testGetAbsolutePublicURL.

@Test(dataProvider = "getAbsolutePublicURLData")
public void testGetAbsolutePublicURL(String protocol, String hostName, int port, String proxyContextPath, String tenantNameFromContext, boolean enableTenantURLSupport, Map<String, String> parameters, String fragment, Map<String, String> fragmentParams, String expected, String urlPath) {
    when(CarbonUtils.getManagementTransport()).thenReturn(protocol);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.HOST_NAME)).thenReturn(hostName);
    when(CarbonUtils.getTransportProxyPort(mockAxisConfiguration, protocol)).thenReturn(port);
    when(ServerConfiguration.getInstance().getFirstProperty(IdentityCoreConstants.PROXY_CONTEXT_PATH)).thenReturn(proxyContextPath);
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(enableTenantURLSupport);
    when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantNameFromContext);
    when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()).thenReturn("carbon.super");
    String absoluteUrl = null;
    try {
        if (MapUtils.isNotEmpty(parameters) && MapUtils.isNotEmpty(fragmentParams)) {
            ServiceURLBuilder serviceURLBuilder = ServiceURLBuilder.create().addPath(urlPath).setFragment(fragment);
            for (String paramKey : parameters.keySet()) {
                serviceURLBuilder.addParameter(paramKey, parameters.get(paramKey));
            }
            for (String fragmentKey : fragmentParams.keySet()) {
                serviceURLBuilder.addFragmentParameter(fragmentKey, fragmentParams.get(fragmentKey));
            }
            absoluteUrl = serviceURLBuilder.build().getAbsolutePublicURL();
        } else if (MapUtils.isNotEmpty(fragmentParams)) {
            absoluteUrl = ServiceURLBuilder.create().addPath(urlPath).setFragment(fragment).addFragmentParameter("key1", "fragment").addFragmentParameter("key2", "fragment").addFragmentParameter("key3", "fragment").addFragmentParameter("key4", "fragment").build().getAbsolutePublicURL();
        } else if (MapUtils.isNotEmpty(parameters)) {
            absoluteUrl = ServiceURLBuilder.create().addPath(urlPath).setFragment(fragment).addParameter("key1", "v").addParameter("key2", "v").addParameter("key3", "v").addParameter("key4", "v").build().getAbsolutePublicURL();
        } else {
            absoluteUrl = ServiceURLBuilder.create().addPath(urlPath).setFragment(fragment).build().getAbsolutePublicURL();
        }
    } catch (URLBuilderException e) {
    // Mock behaviour, hence ignored.
    }
    assertEquals(absoluteUrl, expected);
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project carbon-identity-framework by wso2.

the class JITProvisioningPostAuthenticationHandler method redirectToAccountCreateUI.

/**
 * Call the relevant URL to add the new user.
 *
 * @param externalIdPConfig Relevant external IDP.
 * @param context           Authentication context.
 * @param localClaimValues  Local claim values.
 * @param response          HttpServlet response.
 * @param username          Relevant user name
 * @throws PostAuthenticationFailedException Post Authentication Failed Exception.
 */
private void redirectToAccountCreateUI(ExternalIdPConfig externalIdPConfig, AuthenticationContext context, Map<String, String> localClaimValues, HttpServletResponse response, String username, HttpServletRequest request) throws PostAuthenticationFailedException {
    try {
        ServiceURLBuilder uriBuilder = ServiceURLBuilder.create();
        if (externalIdPConfig.isModifyUserNameAllowed()) {
            context.setProperty(FrameworkConstants.CHANGING_USERNAME_ALLOWED, true);
            uriBuilder = uriBuilder.addPath(FrameworkUtils.getUserNameProvisioningUIUrl());
            uriBuilder.addParameter(FrameworkConstants.ALLOW_CHANGE_USER_NAME, String.valueOf(true));
            if (log.isDebugEnabled()) {
                log.debug(externalIdPConfig.getName() + " allow to change the username, redirecting to " + "registration endpoint to provision the user: " + username);
            }
        } else {
            uriBuilder = uriBuilder.addPath(FrameworkUtils.getPasswordProvisioningUIUrl());
            if (log.isDebugEnabled()) {
                if (externalIdPConfig.isPasswordProvisioningEnabled()) {
                    log.debug(externalIdPConfig.getName() + " supports password provisioning, redirecting to " + "sign up endpoint to provision the user : " + username);
                }
            }
        }
        if (externalIdPConfig.isPasswordProvisioningEnabled()) {
            uriBuilder.addParameter(FrameworkConstants.PASSWORD_PROVISION_ENABLED, String.valueOf(true));
        }
        if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            uriBuilder.addParameter(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME, context.getTenantDomain());
        }
        uriBuilder.addParameter(FrameworkConstants.SERVICE_PROVIDER, context.getSequenceConfig().getApplicationConfig().getApplicationName());
        uriBuilder.addParameter(FrameworkConstants.USERNAME, username);
        uriBuilder.addParameter(FrameworkConstants.SKIP_SIGN_UP_ENABLE_CHECK, String.valueOf(true));
        uriBuilder.addParameter(FrameworkConstants.SESSION_DATA_KEY, context.getContextIdentifier());
        addMissingClaims(uriBuilder, context);
        localClaimValues.forEach(uriBuilder::addParameter);
        response.sendRedirect(uriBuilder.build().getRelativePublicURL());
    } catch (IOException | URLBuilderException e) {
        handleExceptions(String.format(ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getMessage(), username, externalIdPConfig.getName()), ErrorMessages.ERROR_WHILE_TRYING_CALL_SIGN_UP_ENDPOINT_FOR_PASSWORD_PROVISIONING.getCode(), e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) IOException(java.io.IOException) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder)

Example 5 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserAuthenticationEndpointTest method testDeviceAuthorizeForURLBuilderExceptionPath.

/**
 * Test device endpoint throwing URLBuilderException.
 *
 * @param userCode      User code of the user.
 * @param clientId      Consumer key of the application.
 * @param expectedValue Expected http status.
 * @param status        Status of user code.
 * @param uri           Redirection uri.
 * @throws Exception Error while testing device endpoint throwing URLBuilderException.
 */
@Test(dataProvider = "providePostParamsForURLBuilderExceptionPath")
public void testDeviceAuthorizeForURLBuilderExceptionPath(String userCode, String clientId, int expectedValue, String status, String uri) throws Exception {
    mockOAuthServerConfiguration();
    WhiteboxImpl.setInternalState(userAuthenticationEndpoint, "oAuth2AuthzEndpoint", oAuth2AuthzEndpoint);
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    mockStatic(DeviceFlowPersistenceFactory.class);
    when(DeviceFlowPersistenceFactory.getInstance()).thenReturn(deviceFlowPersistenceFactory);
    when(deviceFlowPersistenceFactory.getDeviceFlowDAO()).thenReturn(deviceFlowDAO);
    when(deviceFlowDAO.getClientIdByUserCode(anyString())).thenReturn(clientId);
    when(deviceFlowDAO.getDetailsForUserCode(anyString())).thenReturn(deviceFlowDOAsNotExpired);
    when(deviceFlowDAO.getScopesForUserCode(anyString())).thenReturn(scopes);
    when(httpServletRequest.getParameter(anyString())).thenReturn(userCode);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getAppInformationByClientId(anyString())).thenReturn(oAuthAppDO);
    when(oAuthAppDO.getCallbackUrl()).thenReturn(uri);
    Response response1;
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(ServiceURLBuilder.class);
    when(ServiceURLBuilder.create()).thenReturn(serviceURLBuilder);
    when(serviceURLBuilder.addPath(any())).thenReturn(serviceURLBuilder);
    when(serviceURLBuilder.addParameter(any(), any())).thenReturn(serviceURLBuilder);
    when(serviceURLBuilder.build()).thenThrow(new URLBuilderException("Throwing URLBuilderException."));
    when(serviceURL.getAbsolutePublicURL()).thenReturn(TEST_URL);
    when(oAuth2AuthzEndpoint.authorize(any(CommonAuthRequestWrapper.class), any(HttpServletResponse.class))).thenReturn(response);
    DeviceAuthServiceImpl deviceAuthService = new DeviceAuthServiceImpl();
    userAuthenticationEndpoint = new UserAuthenticationEndpoint();
    userAuthenticationEndpoint.setDeviceAuthService(deviceAuthService);
    WhiteboxImpl.setInternalState(userAuthenticationEndpoint, OAuth2AuthzEndpoint.class, oAuth2AuthzEndpoint);
    response1 = userAuthenticationEndpoint.deviceAuthorize(httpServletRequest, httpServletResponse);
    if (expectedValue == HttpServletResponse.SC_ACCEPTED) {
        Assert.assertNotNull(response1);
    } else {
        Assert.assertNull(response1);
    }
}
Also used : Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeviceAuthServiceImpl(org.wso2.carbon.identity.oauth2.device.api.DeviceAuthServiceImpl) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

URLBuilderException (org.wso2.carbon.identity.core.URLBuilderException)18 IOException (java.io.IOException)5 ServiceURLBuilder (org.wso2.carbon.identity.core.ServiceURLBuilder)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 Test (org.testng.annotations.Test)4 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)4 URISyntaxException (java.net.URISyntaxException)3 HashMap (java.util.HashMap)3 CommonAuthRequestWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper)3 ServiceURL (org.wso2.carbon.identity.core.ServiceURL)3 URI (java.net.URI)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ServletException (javax.servlet.ServletException)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 Matchers.anyString (org.mockito.Matchers.anyString)2 AuthenticationRequestCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry)2