Search in sources :

Example 11 with RequestObjectException

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

the class RequestObjectService method getRequestedClaims.

/**
 * To invoke the RequestObjectPersistenceFactory to retrieve request object.
 *
 * @param token access token Id
 * @return list of claims which have marked as essential in the request object.
 * @throws RequestObjectException
 */
private List<RequestedClaim> getRequestedClaims(String token, boolean isUserInfo) throws RequestObjectException {
    boolean isRequestObjectEnabled = OAuthServerConfiguration.getInstance().isRequestObjectEnabled();
    if (!isRequestObjectEnabled) {
        log.debug("Request Object Flow is disabled, hence dropping the event");
        return Collections.emptyList();
    }
    List<RequestedClaim> essentialClaims;
    if (log.isDebugEnabled()) {
        log.debug("Invoking the RequestObjectPersistenceFactory to retrieve essential claims list.");
    }
    try {
        essentialClaims = OAuthTokenPersistenceFactory.getInstance().getRequestObjectDAO().getRequestedClaims(token, isUserInfo);
    } catch (IdentityOAuth2Exception e) {
        throw new RequestObjectException(e.getMessage());
    }
    return essentialClaims;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) RequestedClaim(org.wso2.carbon.identity.openidconnect.model.RequestedClaim)

Example 12 with RequestObjectException

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

the class RequestObjectService method getRequestedClaimsbySessionDataKey.

/**
 * To invoke the RequestObjectPersistenceFactory to retrieve request object.
 *
 * @param sessionDataKey sessionDataKey
 * @param isUserInfo isUserInfo
 * @return list of claims which have marked as essential in the request object.
 * @throws RequestObjectException
 */
private List<RequestedClaim> getRequestedClaimsbySessionDataKey(String sessionDataKey, boolean isUserInfo) throws RequestObjectException {
    boolean isRequestObjectEnabled = OAuthServerConfiguration.getInstance().isRequestObjectEnabled();
    if (!isRequestObjectEnabled) {
        log.debug("Request Object Flow is disabled, hence dropping the event");
        return Collections.emptyList();
    }
    List<RequestedClaim> essentialClaims;
    if (log.isDebugEnabled()) {
        log.debug("Invoking the RequestObjectPersistenceFactory to retrieve essential claims list " + "by using session data key:" + sessionDataKey + ", isUserInfo: " + isUserInfo);
    }
    try {
        essentialClaims = OAuthTokenPersistenceFactory.getInstance().getRequestObjectDAO().getRequestedClaimsbySessionDataKey(sessionDataKey, isUserInfo);
    } catch (IdentityOAuth2Exception e) {
        throw new RequestObjectException(e.getMessage());
    }
    return essentialClaims;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) RequestedClaim(org.wso2.carbon.identity.openidconnect.model.RequestedClaim)

Example 13 with RequestObjectException

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

the class RequestParamRequestObjectBuilder method buildRequestObject.

/**
 * Builds request object which comes as the value of the request query parameter of OIDC authorization request
 *
 * @param requestObjectParam request object
 * @throws RequestObjectException
 */
@Override
public RequestObject buildRequestObject(String requestObjectParam, OAuth2Parameters oAuth2Parameters) throws RequestObjectException {
    RequestObject requestObject = new RequestObject();
    // Making a copy of requestObjectParam to prevent editing initial reference
    String requestObjectParamValue = requestObjectParam;
    if (isEncrypted(requestObjectParamValue)) {
        requestObjectParamValue = decrypt(requestObjectParamValue, oAuth2Parameters);
        if (isEmpty(requestObjectParamValue)) {
            return requestObject;
        }
    }
    setRequestObjectValues(requestObjectParamValue, requestObject);
    if (log.isDebugEnabled()) {
        log.debug("Request Object extracted from the request: " + requestObjectParam);
    }
    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "Request object parsed successfully.", "parse-request-object", null);
    return requestObject;
}
Also used : RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject)

Example 14 with RequestObjectException

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

the class OAuth2AuthzEndpoint method handlePreConsent.

/**
 * Handle user consent from claims that will be shared in OIDC responses. Claims that require consent will be
 * sent to the consent page as query params. Consent page will interpret the query params and prompt the user
 * for consent.
 *
 * @param oauth2Params
 * @param user                Authenticated User
 * @param useExistingConsents Whether to consider existing user consents
 * @return
 * @throws ConsentHandlingFailedException
 * @throws OAuthSystemException
 */
private String handlePreConsent(OAuth2Parameters oauth2Params, AuthenticatedUser user, boolean useExistingConsents) throws ConsentHandlingFailedException, OAuthSystemException {
    String additionalQueryParam = StringUtils.EMPTY;
    String clientId = oauth2Params.getClientId();
    String spTenantDomain = oauth2Params.getTenantDomain();
    ServiceProvider serviceProvider = getServiceProvider(clientId);
    Map<String, Object> params = new HashMap<>();
    params.put("clientId", clientId);
    try {
        params.put("user", user.getUserId());
    } catch (UserIdNotFoundException e) {
        if (StringUtils.isNotBlank(user.getAuthenticatedSubjectIdentifier())) {
            params.put("user", user.getAuthenticatedSubjectIdentifier());
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Initiating consent handling for user: " + user.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
    }
    if (isConsentHandlingFromFrameworkSkipped(oauth2Params)) {
        if (log.isDebugEnabled()) {
            log.debug("Consent handling from framework skipped for client_id: " + clientId + " of tenantDomain: " + spTenantDomain + " for user: " + user.toFullQualifiedUsername());
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> configs = new HashMap<>();
            configs.put("skipConsent", "true");
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "'skipConsent' is enabled for the OAuth client. Hence consent claims not generated.", "generate-consent-claims", configs);
        }
        return StringUtils.EMPTY;
    }
    try {
        ConsentClaimsData claimsForApproval = getConsentRequiredClaims(user, serviceProvider, useExistingConsents, oauth2Params);
        if (claimsForApproval != null) {
            String requestClaimsQueryParam = null;
            // Get the mandatory claims and append as query param.
            String mandatoryClaimsQueryParam = null;
            // Remove the claims which dont have values given by the user.
            claimsForApproval.setRequestedClaims(removeConsentRequestedNullUserAttributes(claimsForApproval.getRequestedClaims(), user.getUserAttributes(), spTenantDomain));
            List<ClaimMetaData> requestedOidcClaimsList = getRequestedOidcClaimsList(claimsForApproval, oauth2Params, spTenantDomain);
            if (CollectionUtils.isNotEmpty(requestedOidcClaimsList)) {
                requestClaimsQueryParam = REQUESTED_CLAIMS + "=" + buildConsentClaimString(requestedOidcClaimsList);
            }
            if (CollectionUtils.isNotEmpty(claimsForApproval.getMandatoryClaims())) {
                mandatoryClaimsQueryParam = MANDATORY_CLAIMS + "=" + buildConsentClaimString(claimsForApproval.getMandatoryClaims());
            }
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> configs = new HashMap<>();
                List<String> requestedClaims = new ArrayList<>();
                requestedOidcClaimsList.forEach(claim -> requestedClaims.add(claim.getClaimUri()));
                List<String> mandatoryClaims = new ArrayList<>();
                claimsForApproval.getMandatoryClaims().forEach(claim -> mandatoryClaims.add(claim.getClaimUri()));
                configs.put("skipConsent", "false");
                configs.put("requestedClaims", requestedClaims);
                configs.put("mandatoryClaims", mandatoryClaims);
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Consent claims generation successful. Consent claims query parameter: " + additionalQueryParam, "generate-consent-claims", configs);
            }
            additionalQueryParam = buildQueryParamString(requestClaimsQueryParam, mandatoryClaimsQueryParam);
        }
    } catch (UnsupportedEncodingException | SSOConsentServiceException e) {
        String msg = "Error while handling user consent for claim for user: " + user.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain;
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "generate-consent-claims", null);
        }
        throw new ConsentHandlingFailedException(msg, e);
    } catch (ClaimMetadataException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "generate-consent-claims", 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, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "generate-consent-claims", null);
        }
        throw new ConsentHandlingFailedException("Error while getting essential claims for the session data key " + ": " + oauth2Params.getSessionDataKey(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Additional Query param to be sent to consent page for user: " + user.toFullQualifiedUsername() + " for client_id: " + clientId + " is '" + additionalQueryParam + "'");
    }
    return additionalQueryParam;
}
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) ArrayList(java.util.ArrayList) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData) ConsentHandlingFailedException(org.wso2.carbon.identity.oauth.endpoint.exception.ConsentHandlingFailedException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject)

Example 15 with RequestObjectException

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

the class OIDCRequestObjectUtilTest method testBuildRequestObjectTest.

@Test(dataProvider = "TestBuildRequestObjectTest")
public void testBuildRequestObjectTest(String requestObjectString, Map<String, Object> claims, boolean isSigned, boolean isEncrypted, boolean exceptionNotExpected, String errorMsg) throws Exception {
    OAuth2Parameters oAuth2Parameters = new OAuth2Parameters();
    oAuth2Parameters.setTenantDomain("carbon.super");
    oAuth2Parameters.setClientId(TEST_CLIENT_ID_1);
    OAuthAuthzRequest oAuthAuthzRequest = mock(OAuthAuthzRequest.class);
    IdentityEventService eventServiceMock = mock(IdentityEventService.class);
    when(oAuthAuthzRequest.getParam(Constants.REQUEST)).thenReturn(requestObjectString);
    mockStatic(CentralLogMgtServiceComponentHolder.class);
    when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
    when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
    PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
    OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getTenantId("carbon.super")).thenReturn(-1234);
    when((OAuth2Util.getPrivateKey(anyString(), anyInt()))).thenReturn(rsaPrivateKey);
    when(OAuth2Util.getX509CertOfOAuthApp(TEST_CLIENT_ID_1, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(clientKeyStore.getCertificate("wso2carbon"));
    OAuthAppDO oAuthAppDO = new OAuthAppDO();
    when(OAuth2Util.getAppInformationByClientId(TEST_CLIENT_ID_1)).thenReturn(oAuthAppDO);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    RequestObjectValidator requestObjectValidator = PowerMockito.spy(new RequestObjectValidatorImpl());
    when((oauthServerConfigurationMock.getRequestObjectValidator())).thenReturn(requestObjectValidator);
    PowerMockito.doReturn(SOME_SERVER_URL).when(requestObjectValidator, "getTokenEpURL", anyString());
    RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
    Map<String, RequestObjectBuilder> requestObjectBuilderMap = new HashMap<>();
    requestObjectBuilderMap.put(REQUEST_PARAM_VALUE_BUILDER, requestParamRequestObjectBuilder);
    requestObjectBuilderMap.put(REQUEST_URI_PARAM_VALUE_BUILDER, null);
    when((oauthServerConfigurationMock.getRequestObjectBuilders())).thenReturn(requestObjectBuilderMap);
    try {
        OIDCRequestObjectUtil.buildRequestObject(oAuthAuthzRequest, oAuth2Parameters);
    } catch (RequestObjectException e) {
        Assert.assertFalse(exceptionNotExpected, errorMsg + " Request Object Building failed due to " + e.getErrorMessage());
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Matchers.anyString(org.mockito.Matchers.anyString) IdentityEventService(org.wso2.carbon.identity.event.services.IdentityEventService) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

RequestObjectException (org.wso2.carbon.identity.oauth2.RequestObjectException)23 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)9 HashMap (java.util.HashMap)7 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 JOSEException (com.nimbusds.jose.JOSEException)4 ArrayList (java.util.ArrayList)4 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)4 SignedJWT (com.nimbusds.jwt.SignedJWT)3 ParseException (java.text.ParseException)3 Map (java.util.Map)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 JSONObject (net.minidev.json.JSONObject)3 ClaimMetaData (org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData)3 RequestedClaim (org.wso2.carbon.identity.openidconnect.model.RequestedClaim)3 JWEHeader (com.nimbusds.jose.JWEHeader)2 JWEObject (com.nimbusds.jose.JWEObject)2 RSAEncrypter (com.nimbusds.jose.crypto.RSAEncrypter)2 EncryptedJWT (com.nimbusds.jwt.EncryptedJWT)2 List (java.util.List)2 JSONObject (org.json.JSONObject)2