Search in sources :

Example 21 with RequestObjectException

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

the class OAuth2AuthzEndpoint method getRequestedOidcClaimsList.

/**
 * Filter requested claims based on OIDC claims and return the claims which includes in OIDC.
 *
 * @param claimsForApproval         Consent required claims.
 * @param oauth2Params              OAuth parameters.
 * @param spTenantDomain            Tenant domain.
 * @return                          Requested OIDC claim list.
 * @throws RequestObjectException   If an error occurred while getting essential claims for the session data key.
 * @throws ClaimMetadataException   If an error occurred while getting claim mappings.
 */
private List<ClaimMetaData> getRequestedOidcClaimsList(ConsentClaimsData claimsForApproval, OAuth2Parameters oauth2Params, String spTenantDomain) throws RequestObjectException, ClaimMetadataException {
    List<ClaimMetaData> requestedOidcClaimsList = new ArrayList<>();
    List<String> localClaimsOfOidcClaims = new ArrayList<>();
    List<String> localClaimsOfEssentialClaims = new ArrayList<>();
    // Get the claims uri list of all the requested scopes. Eg:- country, email.
    List<String> claimListOfScopes = openIDConnectClaimFilter.getClaimsFilteredByOIDCScopes(oauth2Params.getScopes(), spTenantDomain);
    List<String> essentialRequestedClaims = new ArrayList<>();
    if (oauth2Params.isRequestObjectFlow()) {
        // Get the requested claims came through request object.
        List<RequestedClaim> requestedClaimsOfIdToken = EndpointUtil.getRequestObjectService().getRequestedClaimsForSessionDataKey(oauth2Params.getSessionDataKey(), false);
        List<RequestedClaim> requestedClaimsOfUserInfo = EndpointUtil.getRequestObjectService().getRequestedClaimsForSessionDataKey(oauth2Params.getSessionDataKey(), true);
        // Get the list of id token's essential claims.
        for (RequestedClaim requestedClaim : requestedClaimsOfIdToken) {
            if (requestedClaim.isEssential()) {
                essentialRequestedClaims.add(requestedClaim.getName());
            }
        }
        // Get the list of user info's essential claims.
        for (RequestedClaim requestedClaim : requestedClaimsOfUserInfo) {
            if (requestedClaim.isEssential()) {
                essentialRequestedClaims.add(requestedClaim.getName());
            }
        }
    }
    if (CollectionUtils.isNotEmpty(claimListOfScopes)) {
        // Get the external claims relevant to all oidc scope claims and essential claims.
        Set<ExternalClaim> externalClaimSetOfOidcClaims = ClaimMetadataHandler.getInstance().getMappingsFromOtherDialectToCarbon(OIDC_DIALECT, new HashSet<String>(claimListOfScopes), spTenantDomain);
        /* Get the locally mapped claims for all the external claims of requested scope and essential claims.
            Eg:- http://wso2.org/claims/country, http://wso2.org/claims/emailaddress
             */
        for (ExternalClaim externalClaim : externalClaimSetOfOidcClaims) {
            localClaimsOfOidcClaims.add(externalClaim.getMappedLocalClaim());
        }
    }
    if (CollectionUtils.isNotEmpty(essentialRequestedClaims)) {
        // Get the external claims relevant to all essential requested claims.
        Set<ExternalClaim> externalClaimSetOfEssentialClaims = ClaimMetadataHandler.getInstance().getMappingsFromOtherDialectToCarbon(OIDC_DIALECT, new HashSet<String>(essentialRequestedClaims), spTenantDomain);
        /* Get the locally mapped claims for all the external claims of essential claims.
            Eg:- http://wso2.org/claims/country, http://wso2.org/claims/emailaddress
             */
        for (ExternalClaim externalClaim : externalClaimSetOfEssentialClaims) {
            localClaimsOfEssentialClaims.add(externalClaim.getMappedLocalClaim());
        }
    }
    /* Check whether the local claim of oidc claims contains the requested claims or essential claims of
         request object contains the requested claims, If it contains add it as requested claim.
         */
    for (ClaimMetaData claimMetaData : claimsForApproval.getRequestedClaims()) {
        if (localClaimsOfOidcClaims.contains(claimMetaData.getClaimUri()) || localClaimsOfEssentialClaims.contains(claimMetaData.getClaimUri())) {
            requestedOidcClaimsList.add(claimMetaData);
        }
    }
    return requestedOidcClaimsList;
}
Also used : RequestedClaim(org.wso2.carbon.identity.openidconnect.model.RequestedClaim) ExternalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.ExternalClaim) ArrayList(java.util.ArrayList) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData)

Example 22 with RequestObjectException

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

the class RequestObjectValidatorImpl method checkExpirationTime.

private boolean checkExpirationTime(RequestObject requestObject) throws RequestObjectException {
    Date expirationTime = requestObject.getClaimsSet().getExpirationTime();
    if (expirationTime != null) {
        long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
        long expirationTimeInMillis = expirationTime.getTime();
        long currentTimeInMillis = System.currentTimeMillis();
        if ((currentTimeInMillis + timeStampSkewMillis) > expirationTimeInMillis) {
            String msg = "Request Object is expired." + ", Expiration Time(ms) : " + expirationTimeInMillis + ", TimeStamp Skew : " + timeStampSkewMillis + ", Current Time : " + currentTimeInMillis + ". Token Rejected.";
            logAndReturnFalse(msg);
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("requestObjectExpirationTime", expirationTime);
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Request Object is Expired.", "validate-request-object", null);
            }
            throw new RequestObjectException(RequestObjectException.ERROR_CODE_INVALID_REQUEST, "Request Object " + "is Expired.");
        }
    }
    return true;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) HashMap(java.util.HashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) Date(java.util.Date)

Example 23 with RequestObjectException

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

the class RequestObjectValidatorImpl method getTokenEpURL.

/**
 * Return the alias of the resident IDP to validate the audience value of the Request Object.
 *
 * @param tenantDomain
 * @return tokenEndpoint of the Issuer
 * @throws IdentityOAuth2Exception
 */
protected String getTokenEpURL(String tenantDomain) throws RequestObjectException {
    String residentIdpAlias = StringUtils.EMPTY;
    IdentityProvider residentIdP;
    try {
        residentIdP = IdentityProviderManager.getInstance().getResidentIdP(tenantDomain);
        FederatedAuthenticatorConfig oidcFedAuthn = IdentityApplicationManagementUtil.getFederatedAuthenticator(residentIdP.getFederatedAuthenticatorConfigs(), IdentityApplicationConstants.Authenticator.OIDC.NAME);
        Property idPEntityIdProperty = IdentityApplicationManagementUtil.getProperty(oidcFedAuthn.getProperties(), OIDC_IDP_ENTITY_ID);
        if (idPEntityIdProperty != null) {
            residentIdpAlias = idPEntityIdProperty.getValue();
            if (log.isDebugEnabled()) {
                log.debug("Found IdPEntityID: " + residentIdpAlias + " for tenantDomain: " + tenantDomain);
            }
        }
    } catch (IdentityProviderManagementException e) {
        log.error("Error while loading OAuth2TokenEPUrl of the resident IDP of tenant:" + tenantDomain, e);
        throw new RequestObjectException(OAuth2ErrorCodes.SERVER_ERROR, "Server Error while validating audience " + "of Request Object.");
    }
    if (isEmpty(residentIdpAlias)) {
        residentIdpAlias = IdentityUtil.getProperty(OIDC_ID_TOKEN_ISSUER_ID);
        if (isNotEmpty(residentIdpAlias)) {
            if (log.isDebugEnabled()) {
                log.debug("'IdPEntityID' property was empty for tenantDomain: " + tenantDomain + ". Using " + "OIDC IDToken Issuer value: " + residentIdpAlias + " as alias to identify Resident IDP.");
            }
        }
    }
    return residentIdpAlias;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) FederatedAuthenticatorConfig(org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) Property(org.wso2.carbon.identity.application.common.model.Property) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 24 with RequestObjectException

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

the class RequestParamRequestObjectBuilder method decrypt.

/**
 * Decrypt the request object.
 *
 * @param requestObject    requestObject
 * @param oAuth2Parameters oAuth2Parameters
 * @throws RequestObjectException
 */
@Override
public String decrypt(String requestObject, OAuth2Parameters oAuth2Parameters) throws RequestObjectException {
    EncryptedJWT encryptedJWT;
    try {
        encryptedJWT = EncryptedJWT.parse(requestObject);
        RSAPrivateKey rsaPrivateKey = getRSAPrivateKey(oAuth2Parameters);
        RSADecrypter decrypter = new RSADecrypter(rsaPrivateKey);
        encryptedJWT.decrypt(decrypter);
        JWEObject jweObject = JWEObject.parse(requestObject);
        jweObject.decrypt(decrypter);
        if (jweObject.getPayload() != null && jweObject.getPayload().toString().split(JWT_PART_DELIMITER).length == NUMBER_OF_PARTS_IN_JWS) {
            return jweObject.getPayload().toString();
        } else {
            return new PlainJWT((JWTClaimsSet) encryptedJWT.getJWTClaimsSet()).serialize();
        }
    } catch (JOSEException | IdentityOAuth2Exception | ParseException e) {
        String errorMessage = "Failed to decrypt Request Object";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage + " from " + requestObject, e);
        }
        throw new RequestObjectException(RequestObjectException.ERROR_CODE_INVALID_REQUEST, errorMessage);
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) PlainJWT(com.nimbusds.jwt.PlainJWT) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWEObject(com.nimbusds.jose.JWEObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JOSEException(com.nimbusds.jose.JOSEException) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 25 with RequestObjectException

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

the class OIDCRequestObjectUtil method validateRequestObjectSignature.

/**
 * @param oAuth2Parameters OAuth2 parameters
 * @param requestObject OAuth2 request
 * @param requestObjectValidator OAuth2 Request validator
 * @throws RequestObjectException
 */
public static void validateRequestObjectSignature(OAuth2Parameters oAuth2Parameters, RequestObject requestObject, RequestObjectValidator requestObjectValidator) throws RequestObjectException {
    String clientId = oAuth2Parameters.getClientId();
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId);
    } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "validate-request-object-signature", null);
        throw new RequestObjectException("Error while retrieving app information for client_id: " + clientId + ". Cannot proceed with signature validation", e);
    }
    try {
        // Check whether request object signature validation is enforced.
        if (oAuthAppDO.isRequestObjectSignatureValidationEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("Request Object Signature Verification enabled for client_id: " + clientId);
            }
            if (requestObject.isSigned()) {
                validateSignature(oAuth2Parameters, requestObject, requestObjectValidator);
            } else {
                // If request object is not signed we need to throw an exception.
                if (LoggerUtils.isDiagnosticLogsEnabled()) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("clientId", clientId);
                    Map<String, Object> configs = new HashMap<>();
                    configs.put("requestObjectSignatureValidationEnabled", "true");
                    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Request object signature validation is enabled but request object is not signed.", "validate-request-object-signature", configs);
                }
                throw new RequestObjectException("Request object signature validation is enabled but request " + "object is not signed.");
            }
        } else {
            // the request object is signed.
            if (requestObject.isSigned()) {
                validateSignature(oAuth2Parameters, requestObject, requestObjectValidator);
            }
        }
    } catch (RequestObjectException e) {
        if (StringUtils.isNotBlank(e.getErrorMessage()) && e.getErrorMessage().contains("signature verification " + "failed")) {
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", oAuth2Parameters.getClientId());
                Map<String, Object> configs = new HashMap<>();
                configs.put("requestObjectSignatureValidationEnabled", Boolean.toString(oAuthAppDO.isRequestObjectSignatureValidationEnabled()));
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Request Object signature verification failed.", "validate-request-object-signature", configs);
            }
        }
        throw e;
    }
    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.SUCCESS, "Request Object signature verification is successful.", "validate-request-object-signature", null);
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) HashMap(java.util.HashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) HashMap(java.util.HashMap) Map(java.util.Map) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

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