Search in sources :

Example 16 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleFailedAuthentication.

private Response handleFailedAuthentication(OAuthMessage oAuthMessage, OAuth2Parameters oauth2Params, AuthenticationResult authnResult) throws URISyntaxException {
    OAuthErrorDTO oAuthErrorDTO = EndpointUtil.getOAuth2Service().handleAuthenticationFailure(oauth2Params);
    OAuthProblemException oauthException = buildOAuthProblemException(authnResult, oAuthErrorDTO);
    return handleFailedState(oAuthMessage, oauth2Params, oauthException);
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthErrorDTO(org.wso2.carbon.identity.oauth.dto.OAuthErrorDTO)

Example 17 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters 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 18 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method buildAuthRequest.

private OAuth2AuthorizeReqDTO buildAuthRequest(OAuth2Parameters oauth2Params, SessionDataCacheEntry sessionDataCacheEntry, HttpRequestHeaderHandler httpRequestHeaderHandler) {
    OAuth2AuthorizeReqDTO authzReqDTO = new OAuth2AuthorizeReqDTO();
    authzReqDTO.setCallbackUrl(oauth2Params.getRedirectURI());
    authzReqDTO.setConsumerKey(oauth2Params.getClientId());
    authzReqDTO.setResponseType(oauth2Params.getResponseType());
    authzReqDTO.setScopes(oauth2Params.getScopes().toArray(new String[oauth2Params.getScopes().size()]));
    authzReqDTO.setUser(sessionDataCacheEntry.getLoggedInUser());
    authzReqDTO.setACRValues(oauth2Params.getACRValues());
    authzReqDTO.setNonce(oauth2Params.getNonce());
    authzReqDTO.setPkceCodeChallenge(oauth2Params.getPkceCodeChallenge());
    authzReqDTO.setPkceCodeChallengeMethod(oauth2Params.getPkceCodeChallengeMethod());
    authzReqDTO.setTenantDomain(oauth2Params.getTenantDomain());
    authzReqDTO.setAuthTime(sessionDataCacheEntry.getAuthTime());
    authzReqDTO.setMaxAge(oauth2Params.getMaxAge());
    authzReqDTO.setEssentialClaims(oauth2Params.getEssentialClaims());
    authzReqDTO.setSessionDataKey(oauth2Params.getSessionDataKey());
    authzReqDTO.setRequestObjectFlow(oauth2Params.isRequestObjectFlow());
    authzReqDTO.setIdpSessionIdentifier(sessionDataCacheEntry.getSessionContextIdentifier());
    authzReqDTO.setLoggedInTenantDomain(oauth2Params.getLoginTenantDomain());
    if (sessionDataCacheEntry.getParamMap() != null && sessionDataCacheEntry.getParamMap().get(OAuthConstants.AMR) != null) {
        authzReqDTO.addProperty(OAuthConstants.AMR, sessionDataCacheEntry.getParamMap().get(OAuthConstants.AMR));
    }
    // Set Selected acr value.
    String[] sessionIds = sessionDataCacheEntry.getParamMap().get(FrameworkConstants.SESSION_DATA_KEY);
    if (ArrayUtils.isNotEmpty(sessionIds)) {
        String commonAuthSessionId = sessionIds[0];
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(commonAuthSessionId, oauth2Params.getLoginTenantDomain());
        if (sessionContext != null && sessionContext.getSessionAuthHistory() != null) {
            authzReqDTO.setSelectedAcr(sessionContext.getSessionAuthHistory().getSelectedAcrValue());
        }
    }
    // Adding Httprequest headers and cookies in AuthzDTO.
    authzReqDTO.setHttpRequestHeaders(httpRequestHeaderHandler.getHttpRequestHeaders());
    authzReqDTO.setCookie(httpRequestHeaderHandler.getCookies());
    return authzReqDTO;
}
Also used : OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)

Example 19 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleFormPostResponseMode.

private Response handleFormPostResponseMode(OAuthMessage oAuthMessage, OIDCSessionState sessionState, String redirectURL) {
    String authenticatedIdPs = oAuthMessage.getSessionDataCacheEntry().getAuthenticatedIdPs();
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    boolean isOIDCRequest = OAuth2Util.isOIDCAuthzRequest(oauth2Params.getScopes());
    String sessionStateValue = null;
    if (isOIDCRequest) {
        sessionState.setAddSessionState(true);
        sessionStateValue = manageOIDCSessionState(oAuthMessage, sessionState, oauth2Params, getLoggedInUser(oAuthMessage).getAuthenticatedSubjectIdentifier(), redirectURL, oAuthMessage.getSessionDataCacheEntry());
    }
    return Response.ok(createFormPage(redirectURL, oauth2Params.getRedirectURI(), authenticatedIdPs, sessionStateValue)).build();
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)

Example 20 with OAuth2Parameters

use of org.wso2.carbon.identity.oauth2.model.OAuth2Parameters in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method storeUserConsent.

private void storeUserConsent(OAuthMessage oAuthMessage, String consent) throws OAuthSystemException {
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    String applicationName = oauth2Params.getApplicationName();
    AuthenticatedUser loggedInUser = getLoggedInUser(oAuthMessage);
    String clientId = oauth2Params.getClientId();
    ServiceProvider serviceProvider = getServiceProvider(oauth2Params.getClientId());
    if (!isConsentSkipped(serviceProvider)) {
        boolean approvedAlways = OAuthConstants.Consent.APPROVE_ALWAYS.equals(consent);
        if (approvedAlways) {
            OpenIDConnectUserRPStore.getInstance().putUserRPToStore(loggedInUser, applicationName, true, clientId);
            if (hasPromptContainsConsent(oauth2Params)) {
                EndpointUtil.storeOAuthScopeConsent(loggedInUser, oauth2Params, true);
            } else {
                EndpointUtil.storeOAuthScopeConsent(loggedInUser, oauth2Params, false);
            }
        }
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Aggregations

OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)40 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)23 HashMap (java.util.HashMap)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 Test (org.testng.annotations.Test)19 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)17 Matchers.anyString (org.mockito.Matchers.anyString)14 BeforeTest (org.testng.annotations.BeforeTest)13 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)13 RequestObjectException (org.wso2.carbon.identity.oauth2.RequestObjectException)12 JSONObject (org.json.JSONObject)10 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)9 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)8 ArrayList (java.util.ArrayList)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)7 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)7 SessionDataCacheKey (org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey)7 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)7 URI (java.net.URI)6