Search in sources :

Example 61 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handlePostConsent.

private void handlePostConsent(OAuthMessage oAuthMessage) throws ConsentHandlingFailedException {
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oauth2Params.getClientId());
    setSPAttributeToRequest(oAuthMessage.getRequest(), oauth2Params.getApplicationName(), tenantDomain);
    String spTenantDomain = oauth2Params.getTenantDomain();
    AuthenticatedUser loggedInUser = getLoggedInUser(oAuthMessage);
    String clientId = oauth2Params.getClientId();
    ServiceProvider serviceProvider;
    if (log.isDebugEnabled()) {
        log.debug("Initiating post user consent handling for user: " + loggedInUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
    }
    try {
        if (isConsentHandlingFromFrameworkSkipped(oauth2Params)) {
            if (log.isDebugEnabled()) {
                log.debug("Consent handling from framework skipped for client_id: " + clientId + " of tenantDomain: " + spTenantDomain + " for user: " + loggedInUser.toFullQualifiedUsername() + ". " + "Therefore handling post consent is not applicable.");
            }
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", clientId);
                Map<String, Object> configs = new HashMap<>();
                configs.put("skipConsent", "true");
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Consent is disabled for the OAuth client.", "handle-consent", configs);
            }
            return;
        }
        List<Integer> approvedClaimIds = getUserConsentClaimIds(oAuthMessage);
        serviceProvider = getServiceProvider(clientId);
        /*
                With the current implementation of the SSOConsentService we need to send back the original
                ConsentClaimsData object we got during pre consent stage. Currently we are repeating the API call
                during post consent handling to get the original ConsentClaimsData object (Assuming there is no
                change in SP during pre-consent and post-consent).

                The API on the SSO Consent Service will be improved to avoid having to send the original
                ConsentClaimsData object.
             */
        ConsentClaimsData value = getConsentRequiredClaims(loggedInUser, serviceProvider, oauth2Params);
        /*
                It is needed to pitch the consent required claims with the OIDC claims. otherwise the consent of the
                the claims which are not in the OIDC claims will be saved as consent denied.
            */
        if (value != null) {
            // Remove the claims which dont have values given by the user.
            value.setRequestedClaims(removeConsentRequestedNullUserAttributes(value.getRequestedClaims(), loggedInUser.getUserAttributes(), spTenantDomain));
            List<ClaimMetaData> requestedOidcClaimsList = getRequestedOidcClaimsList(value, oauth2Params, spTenantDomain);
            value.setRequestedClaims(requestedOidcClaimsList);
        }
        // Call framework and create the consent receipt.
        if (log.isDebugEnabled()) {
            log.debug("Creating user consent receipt for user: " + loggedInUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
        }
        Map<String, Object> params;
        if (hasPromptContainsConsent(oauth2Params)) {
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                params = new HashMap<>();
                params.put("clientId", clientId);
                params.put("prompt", oauth2Params.getPrompt());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, null, "hand-over-to-consent-service", null);
            }
            getSSOConsentService().processConsent(approvedClaimIds, serviceProvider, loggedInUser, value, true);
        } else {
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                params = new HashMap<>();
                params.put("clientId", clientId);
                params.put("prompt", oauth2Params.getPrompt());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, null, "hand-over-to-consent-service", null);
            }
            getSSOConsentService().processConsent(approvedClaimIds, serviceProvider, loggedInUser, value, false);
        }
    } catch (OAuthSystemException | SSOConsentServiceException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "process-consent", null);
        }
        String msg = "Error while processing consent of user: " + loggedInUser.toFullQualifiedUsername() + " for " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain;
        throw new ConsentHandlingFailedException(msg, e);
    } catch (ClaimMetadataException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, String.format("Error occurred while getting " + "claim mappings for %s.", OIDC_DIALECT), "process-consent", null);
        }
        throw new ConsentHandlingFailedException("Error while getting claim mappings for " + OIDC_DIALECT, e);
    } catch (RequestObjectException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, String.format("Error occurred while getting essential claims for the session data key : %s.", oauth2Params.getSessionDataKey()), "process-consent", null);
        }
        throw new ConsentHandlingFailedException("Error while getting essential claims for the session data key " + ": " + oauth2Params.getSessionDataKey(), e);
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) ConsentHandlingFailedException(org.wso2.carbon.identity.oauth.endpoint.exception.ConsentHandlingFailedException) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject)

Example 62 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpoint method handleErrorResponse.

private Response handleErrorResponse(OAuth2AccessTokenRespDTO oauth2AccessTokenResp) throws OAuthSystemException {
    // if there is an auth failure, HTTP 401 Status Code should be sent back to the client.
    if (OAuth2ErrorCodes.INVALID_CLIENT.equals(oauth2AccessTokenResp.getErrorCode())) {
        return handleBasicAuthFailure(oauth2AccessTokenResp.getErrorMsg());
    } else if (SQL_ERROR.equals(oauth2AccessTokenResp.getErrorCode())) {
        return handleSQLError();
    } else if (OAuth2ErrorCodes.SERVER_ERROR.equals(oauth2AccessTokenResp.getErrorCode())) {
        return handleServerError();
    } else {
        // Otherwise send back HTTP 400 Status Code
        OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(oauth2AccessTokenResp.getErrorCode()).setErrorDescription(oauth2AccessTokenResp.getErrorMsg()).buildJSONMessage();
        ResponseHeader[] headers = oauth2AccessTokenResp.getResponseHeaders();
        ResponseBuilder respBuilder = Response.status(response.getResponseStatus());
        if (headers != null) {
            for (ResponseHeader header : headers) {
                if (header != null) {
                    respBuilder.header(header.getKey(), header.getValue());
                }
            }
        }
        return respBuilder.entity(response.getBody()).build();
    }
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) OAuthTokenResponseBuilder(org.apache.oltu.oauth2.as.response.OAuthASResponse.OAuthTokenResponseBuilder) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 63 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserAuthenticationEndpoint method handleURISyntaxException.

private Response handleURISyntaxException(URISyntaxException e) throws OAuthSystemException {
    log.error("Error while parsing string as an URI reference.", e);
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).setError(OAuth2ErrorCodes.SERVER_ERROR).setErrorDescription("Internal Server Error").buildJSONMessage();
    return Response.status(response.getResponseStatus()).header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE, EndpointUtil.getRealmInfo()).entity(response.getBody()).build();
}
Also used : OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 64 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserAuthenticationEndpoint method handleURLBuilderException.

private Response handleURLBuilderException(URLBuilderException e) throws OAuthSystemException {
    log.error("Error occurred while sending request to authentication framework.", e);
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).setError(OAuth2ErrorCodes.SERVER_ERROR).setErrorDescription("Internal Server Error").buildJSONMessage();
    return Response.status(response.getResponseStatus()).header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE, EndpointUtil.getRealmInfo()).entity(response.getBody()).build();
}
Also used : OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Example 65 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleFormPostMode.

private OAuthResponse handleFormPostMode(OAuthMessage oAuthMessage, OAuthASResponse.OAuthAuthorizationResponseBuilder builder, String redirectURL) throws OAuthSystemException {
    OAuthResponse oauthResponse;
    String authenticatedIdPs = oAuthMessage.getSessionDataCacheEntry().getAuthenticatedIdPs();
    if (authenticatedIdPs != null && !authenticatedIdPs.isEmpty()) {
        builder.setParam(AUTHENTICATED_ID_PS, oAuthMessage.getSessionDataCacheEntry().getAuthenticatedIdPs());
    }
    oauthResponse = builder.location(redirectURL).buildJSONMessage();
    return oauthResponse;
}
Also used : OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)103 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)57 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)51 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)49 IOException (java.io.IOException)41 Request (okhttp3.Request)29 Response (okhttp3.Response)29 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)23 Builder (okhttp3.Request.Builder)19 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)18 URI (java.net.URI)17 Map (java.util.Map)16 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)15 MediaType (okhttp3.MediaType)14 RequestBody (okhttp3.RequestBody)14 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)13 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12