Search in sources :

Example 6 with URLBuilderException

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

the class OAuth2AuthzEndpoint method handleAuthFlowThroughFramework.

/**
 * This method use to call authentication framework directly via API other than using HTTP redirects.
 * Sending wrapper request object to doGet method since other original request doesn't exist required parameters
 * Doesn't check SUCCESS_COMPLETED since taking decision with INCOMPLETE status
 *
 * @param type authenticator type
 * @throws URISyntaxException
 * @throws InvalidRequestParentException
 * @Param type OAuthMessage
 */
private Response handleAuthFlowThroughFramework(OAuthMessage oAuthMessage, String type) throws URISyntaxException, InvalidRequestParentException {
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", oAuthMessage.getClientId());
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Forward authorization request to framework for user authentication.", "hand-over-to-framework", null);
    }
    try {
        String sessionDataKey = (String) oAuthMessage.getRequest().getAttribute(FrameworkConstants.SESSION_DATA_KEY);
        CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
        CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(oAuthMessage.getRequest());
        requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
        requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
        CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(oAuthMessage.getResponse());
        commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
        Object attribute = oAuthMessage.getRequest().getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
        if (attribute != null) {
            if (attribute == AuthenticatorFlowStatus.INCOMPLETE) {
                if (responseWrapper.isRedirect()) {
                    return Response.status(HttpServletResponse.SC_FOUND).location(buildURI(responseWrapper.getRedirectURL())).build();
                } else {
                    return Response.status(HttpServletResponse.SC_OK).entity(responseWrapper.getContent()).build();
                }
            } else {
                return authorize(requestWrapper, responseWrapper);
            }
        } else {
            requestWrapper.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.UNKNOWN);
            return authorize(requestWrapper, responseWrapper);
        }
    } catch (ServletException | IOException | URLBuilderException e) {
        log.error("Error occurred while sending request to authentication framework.");
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oAuthMessage.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "hand-over-to-framework", null);
        }
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 7 with URLBuilderException

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

the class DeviceEndpoint method authorize.

@POST
@Path("/")
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response authorize(@Context HttpServletRequest request, MultivaluedMap<String, String> paramMap, @Context HttpServletResponse response) throws IdentityOAuth2Exception, OAuthSystemException {
    OAuthClientAuthnContext oAuthClientAuthnContext = getValidationObject(request);
    if (!oAuthClientAuthnContext.isAuthenticated()) {
        return handleErrorResponse(oAuthClientAuthnContext);
    }
    try {
        validateRepeatedParams(request, paramMap);
        String deviceCode = UUID.randomUUID().toString();
        String scopes = request.getParameter(Constants.SCOPE);
        String userCode = getUniqueUserCode(deviceCode, oAuthClientAuthnContext.getClientId(), scopes);
        String redirectionUri = ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).build().getAbsolutePublicURL();
        String redirectionUriComplete = ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("user_code", userCode).build().getAbsolutePublicURL();
        return buildResponseObject(deviceCode, userCode, redirectionUri, redirectionUriComplete);
    } catch (IdentityOAuth2Exception e) {
        return handleIdentityOAuth2Exception(e);
    } catch (TokenEndpointBadRequestException e) {
        return handleTokenEndpointBadRequestException(e);
    } catch (URLBuilderException e) {
        return handleURLBuilderException(e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) TokenEndpointBadRequestException(org.wso2.carbon.identity.oauth.endpoint.exception.TokenEndpointBadRequestException) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 8 with URLBuilderException

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

the class UserAuthenticationEndpoint method getRedirectionURI.

/**
 * This method is used to generate the redirection URI.
 *
 * @param appName Service provider name.
 * @return Redirection URI
 */
private String getRedirectionURI(String appName) throws URISyntaxException, URLBuilderException {
    try {
        String pageURI = ServiceURLBuilder.create().addPath(Constants.DEVICE_SUCCESS_ENDPOINT_PATH).build().getAbsolutePublicURL();
        URIBuilder uriBuilder = new URIBuilder(pageURI);
        uriBuilder.addParameter(Constants.APP_NAME, appName);
        return uriBuilder.build().toString();
    } catch (URLBuilderException e) {
        log.error("Error occurred when getting the redirection URI.", e);
        throw new URLBuilderException("Error occurred while sending request to authentication framework.", e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 9 with URLBuilderException

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

the class OAuth2Util method getIssuerLocation.

/**
 * Used to get the issuer url for a given tenant.
 *
 * @param tenantDomain Tenant domain.
 * @return Token issuer url.
 * @throws IdentityOAuth2Exception IdentityOAuth2Exception.
 */
public static String getIssuerLocation(String tenantDomain) throws IdentityOAuth2Exception {
    /*
        * IMPORTANT:
        * This method should only honor the given tenant.
        * Do not add any auto tenant resolving logic.
        */
    if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
        try {
            startTenantFlow(tenantDomain);
            return ServiceURLBuilder.create().addPath(OAUTH2_TOKEN_EP_URL).build().getAbsolutePublicURL();
        } catch (URLBuilderException e) {
            String errorMsg = String.format("Error while building the absolute url of the context: '%s',  for the" + " tenant domain: '%s'", OAUTH2_TOKEN_EP_URL, tenantDomain);
            throw new IdentityOAuth2Exception(errorMsg, e);
        } finally {
            endTenantFlow();
        }
    } else {
        IdentityProvider identityProvider = getResidentIdp(tenantDomain);
        FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs();
        // Get OIDC authenticator
        FederatedAuthenticatorConfig oidcAuthenticatorConfig = IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME);
        return IdentityApplicationManagementUtil.getProperty(oidcAuthenticatorConfig.getProperties(), IDP_ENTITY_ID).getValue();
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider)

Example 10 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-provisioning-scim2 by wso2-extensions.

the class IdentityResourceURLBuilderTest method testBuild.

@Test(dataProvider = "dataProviderForBuild")
public void testBuild(boolean isTenantQualifiedUrlsEnabled, String url, String resource, boolean throwError, String expected) throws NotFoundException, URLBuilderException {
    when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled);
    when(mockServiceURLBuilder.build()).thenAnswer(invocationOnMock -> {
        if (throwError) {
            throw new URLBuilderException("Protocol of service URL is not available.");
        }
        return mockServiceUrl;
    });
    when(mockServiceUrl.getAbsolutePublicURL()).thenReturn(url);
    IdentityResourceURLBuilder identityResourceURLBuilder = new IdentityResourceURLBuilder();
    identityResourceURLBuilder.setEndpointURIMap(DUMMY_ENDPOINT_URI_MAP);
    String buildValue = identityResourceURLBuilder.build(resource);
    assertEquals(buildValue, expected);
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test) 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